How to calculate date and time difference in Java

time-date-different-in-Java

In this tutorial, we show you 2 examples to calculate date / time difference in Java :

  1. Manual time calculation.
  2. Joda time library.

1. Manual time calculation

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :


1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
DateDifferentExample.java

package com.mkyong.date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

	public static void main(String[] args) {

		String dateStart = "01/14/2012 09:29:58";
		String dateStop = "01/15/2012 10:31:48";

		//HH converts hour in 24 hours format (0-23), day calculation
		SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

		Date d1 = null;
		Date d2 = null;

		try {
			d1 = format.parse(dateStart);
			d2 = format.parse(dateStop);

			//in milliseconds
			long diff = d2.getTime() - d1.getTime();

			long diffSeconds = diff / 1000 % 60;
			long diffMinutes = diff / (60 * 1000) % 60;
			long diffHours = diff / (60 * 60 * 1000) % 24;
			long diffDays = diff / (24 * 60 * 60 * 1000);

			System.out.print(diffDays + " days, ");
			System.out.print(diffHours + " hours, ");
			System.out.print(diffMinutes + " minutes, ");
			System.out.print(diffSeconds + " seconds.");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Result


1 days, 1 hours, 1 minutes, 50 seconds.
Why seconds and minutes need %60, and hours %24?

If you change it to


long diffSeconds = diff / 1000;

The result will be


1 days, 1 hours, 1 minutes, 90110 seconds.

The “90110” is the total number of seconds difference between date1 and date2, this is correct if you want to know the differences in seconds ONLY.

To display difference in “day, hour, minute and second” format, you should use a modulus (%60) to cut off the remainder of seconds (90060). Got it? The idea is applied in minutes (%60) and hours (%24) as well.


90110 % 60 = 50 seconds (you want this)
90110 - 50 = 90060 seconds (you dont want this)

2. Joda Time Example

Here’s the equivalent example, but using Joda time to calculate differences between two dates.

P.S This example is using joda-time-2.1.jar

JodaDateDifferentExample.java

package com.mkyong.date;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;

public class JodaDateDifferentExample {

  public static void main(String[] args) {

	String dateStart = "01/14/2012 09:29:58";
	String dateStop = "01/15/2012 10:31:48";

	SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

	Date d1 = null;
	Date d2 = null;

	try {
		d1 = format.parse(dateStart);
		d2 = format.parse(dateStop);

		DateTime dt1 = new DateTime(d1);
		DateTime dt2 = new DateTime(d2);

		System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
		System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
		System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
		System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");

	 } catch (Exception e) {
		e.printStackTrace();
	 }

  }

}

Result


1 days, 1 hours, 1 minutes, 50 seconds.

Do comment below if you have alternative ways 🙂

References

  1. Second in Wikipedia
  2. Joda time official site

41 comments on “How to calculate date and time difference in Java

  1. Hi,

    Nice article .I want to know how can i get the difference in milliseconds along with other time unit . like converting to hour:minute:second:millisecond could you please help me out

  2. Hi All,
    I have a question related to the above post.

    Could anyone please help me in writing a code/Logic/ Algorithm to find the day difference between 2 dates without using any Java library functions?
    Note: Consider leap year also
    Performance too should be considered

  3. Hai, I have a question in java.Program in Java to get the current time in any website and show as output?
    I need your support.

  4. You code does not work. I got below error both with constructor Period(date1, date2) and daysBetween(date1, date2)

    “The method daysBetween(ReadableInstant, ReadableInstant) in the type Days is not applicable for the arguments (Date, Date)”.

    I am running this code on java 1.6. Is this problem with Java version ?

  5. Not sure if I’m missing something, but a simple direct manual approach using difference doesn’t work for me. Ex. Using 11/2/14 and 11/3/14, diff comes back as 90,000 ms. The issue isn’t the subtraction, but rather getTime returns 1,414,998,000,000 for 11/3/14 and 1,414,908,000,000 for 11/2/14 so the diff is 90,000,000 ms (not 86,400,000 ms).

    1. Oops. I spoke a bit too early. After a bit more testing, my issue was simply needing to be specific on the date, time, and time zone entered. Code worked fine after that.

  6. Man I like ur tutorials, very good and easy written. But this one is wrong, the modulo % is ruining all my results, instead of x minutes i was getting x%60 minutes (too small).

  7. I don’t think that using the constant 86400000 is correct in every case: if you have the moment of the change from daylight saving time to standard time or vice versa, you will get incorrect results.

  8. Hi,
    I found example that manual time calculations gives wrong result, when JodaTime calulation gives correct one. For example, we have two date times:
    1) 2010-12-06 00:00:00
    2) 2011-06-14 00:00:00

    Days difference for manual calculation gives: 189 days. Day difference for Joda Time calculation gives: 190 days. Moreover, I took “paper calendar”, counted by hand and received 190 days difference.

    Check out my example code:

    public void testTimeDifference() {

    String dateStart = "2010-12-06 00:00:00";
    String dateStop = "2011-06-14 00:00:00";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
    Date d1 = format.parse(dateStart);
    Date d2 = format.parse(dateStop);

    //--------------------------//
    // RESULTS //
    //--------------------------//

    long diff = d2.getTime() - d1.getTime();
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("DAYS DIFFERENCE: " + diffDays);

    //--------------------------//
    // JODA-TIME RESULTS //
    //--------------------------//

    DateTime dt1 = new DateTime(d1);
    DateTime dt2 = new DateTime(d2);
    System.out.println("DAYS DIFFERENCE (JODA-TIME): " + Days.daysBetween(dt1, dt2).getDays());
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

  9. You should (almost) *never* manually perform date calculations, except if you’re OK with potentially producing bogus data. This is because no one sane will simply *ever* think of all the date crap, such as leap years, leap seconds, daylight savings time, time zones, inofficial time zones, and what not.

  10. your code doesnt work for me.
    >The method daysBetween(ReadableInstant, ReadableInstant) in the type Days is not applicable for the arguments (Date, Date)

  11. In code:
    {code}
    long diffSeconds = diff / 1000 % 60;
    long diffMinutes = diff / (60 * 1000) % 60;

    {code}
    You can consider using TimeUnit class from java.util.concurrent package. Code would be like bellow:
    {code}
    long diffSeconds = TimeUnit.MILLISECONDS.toSeconds(diff) % 60;
    long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff) % 60;
    long diffHours = TimeUnit.MILLISECONDS.toHours(diff) % 24;
    long diffDays = TimeUnit.MILLISECONDS.toDays(diff);
    {code}

  12. Did you consider using the Joda Period object? I think it makes more readable code :

    import org.joda.time.DateTime;
    import org.joda.time.Period;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    public class JodaDatePeriodDifferentExample {
    
        public static void main(String[] args) {
    
            String dateStart = "01/14/2012 09:29:58";
            String dateStop = "01/15/2012 10:31:48";
    
            final DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
    
            DateTime dt1 = format.parseDateTime(dateStart);
            DateTime dt2 = format.parseDateTime(dateStop);
    
            final Period period = new Period(dt1,dt2);
    
            System.out.print(period.getDays()+" days, ");
            System.out.print(period.getHours()+" hours, ");
            System.out.print(period.getMinutes()+" minutes, ");
            System.out.print(period.getSeconds()+" seconds.");
    
        }
    }
    
    1. public class JodaDatePeriod {

      public static void main(String[] args) {

      String dateStart = “June 01, 2013”;
      String dateStop = “June 30, 2013”;

      final DateTimeFormatter format = DateTimeFormat.forPattern(“MMMM dd, yyyy”);

      DateTime date1 = format.parseDateTime(dateStart);
      DateTime date2 = format.parseDateTime(dateStop);

      final Period period = new Period(date1, date2);

      System.out.println(period.getDays() + ” Days”);
      System.out.println(period.getHours() + ” Hours”);
      System.out.println(period.getMinutes() + ” Minutes”);
      System.out.println(period.getSeconds() + ” Seconds”);
      }
      }

      here’s my code and why the period shown just 1 day?

    2. I had to use final Period period = new Period(dt1, dt2, PeriodType.days());
      Else it seems I was getting spurious results on period.getDays();

      I was using DateTimeFormatter format = DateTimeFormat.forPattern(“dd/MM/yyyy”); // With dates such as “28/07/2018”
      Not sure if that made any difference.

Leave a Comment

Your email address will not be published. Required fields are marked *