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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Selvaram

    Very simple to calculate days between dates. Probably this is the most reliable site ever..!!! Thanks again..

  • invalide code

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

  • Valéria Martins

    Thanks!! very good!

  • http://www.javadiscover.com Anand Kumar

    get your list of date and time questions with sample code in java – http://www.javadiscover.com/search/label/Date%20and%20Time

  • http://codenirvana.blogspot.in/ Code Nirvana
    System.out.print("Hello Guys!");

    Thanks for sharing such a nice ideas and codes.
    for more java methods and examples follow my blog:
    http://codenirvana.blogspot.in/search/label/Java

  • http://carlos-garcia.es Carlos García

    Hi,

    On apache commons lang library, you have the class org.apache.commons.lang.time.DateUtils with several methods to work with dates. (add, compare, etc)

  • http://[email protected] Stefan

    http://infiniteundo.com/post/25509354022/more-falsehoods-programmers-believe-about-time-wisdom

    Just in case people really think a minute is always 60 seconds and similar stuff.

  • http://mballem.wordpress.com/ Marcio

    Very good.

  • Srichandar

    Very clear explanation and comparision…

  • Abdul Gafoor

    Funtastic!!!

  • Rafal

    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}

    • http://www.mkyong.com mkyong

      Thanks for your input of TimeUnit, I think I should updae above article again :)

  • stefanodp

    thanks for the tutorial, it is very clear

  • Andrew MacGilvery

    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.");
     
        }
    }
    • http://www.mkyong.com mkyong

      wow, Andrew, your code is great! Joda period looks much better :) Thanks for your code.

    • Kiyongs

      I’ve been using the Joda libraries.
      Thanks for the Information with Period.
      I like that.

    • http://keda87.wordpress.com Keda87

      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?

  • http://mudassirshahzad.com Mudassir Shahzad

    Elegant as ever!