How to Calculate Time Difference in Java?

Given two strings of time, you may want to calculate the difference between them. The following provide a simple solution.

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main {
	public static void main(String[] args) throws Exception{
		String time1 = "12:00:00";
		String time2 = "12:01:00";
 
		SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
		Date date1 = format.parse(time1);
		Date date2 = format.parse(time2);
		long difference = date2.getTime() - date1.getTime();
		System.out.println(difference/1000);
	}
}

Output:

60

Note that the different is in milliseconds, it needs to be divided by 1000 to get the number of seconds. You can easily change the parameter of SimpleDateFormat to use other format of time. For example,”HH:mm:ss.SSS” will also take the milliseconds. For more information about SimpleDateFormat, go to its Java Doc.

Leave a Comment