Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
41 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Othmanebz
7 years ago

How to get Year and month difference too ?

Dhiraj
8 years ago

i want to calculate time difference in 12 hour time format, how to do it?

Anand
8 years ago

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.

$neha
9 years ago

Thank It useful for me 🙂

Ashish Ratan
10 years ago

How to get Year and month difference too ?

Vaishnavi
5 years ago

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

Othmanebz
7 years ago

And for Years ?

srinu
9 years ago

good explanation!!!!!!

Vidhya
9 years ago

thank you, code helped me, simple way

CJacobME
10 years ago

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.

Andrew MacGilvery
11 years ago

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.");

    }
}
Gary
5 years ago

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.

Keda87
10 years ago

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?

Kiyongs
11 years ago

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

Suman
4 years ago

How to get / find difference of two times in java i.e 11:55:45 pm to next day 12:05:40 am in Java kindly reply me anyone

Rajani Sreejith
4 years ago

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

Surinder
9 years ago

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 ?

Eliryo
7 years ago
Reply to  Surinder

The Period contructor and also the method daysBetween want two DateTime parameters, non Date type 🙂

Diego Manuel Benitez Enciso
9 years ago

excelente tutorial

Radek
10 years ago

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();
}
}

Lukas Eder
10 years ago

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.

Selvaram
10 years ago

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

invalide code
10 years ago

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
10 years ago

Thanks!! very good!

Anand Kumar
10 years ago

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

Carlos García
11 years ago

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)

Marcio
11 years ago

Very good.

Srichandar
11 years ago

Very clear explanation and comparision…

Abdul Gafoor
11 years ago

Funtastic!!!

Rafal
11 years ago

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}

stefanodp
11 years ago

thanks for the tutorial, it is very clear

Mudassir Shahzad
11 years ago

Elegant as ever!

Ahmad Reza
6 years ago

Nice thanks Alot

Rajesh
6 years ago

Thank you so much…this code really helped…