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
author image

mkyong

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. Read all published posts by

Comments

avatar
newest oldest most voted
Othmanebz
Guest
Othmanebz

How to get Year and month difference too ?

Lukas Eder
Guest
Lukas Eder

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.

Ashish Ratan
Guest
Ashish Ratan

How to get Year and month difference too ?

Dhiraj
Guest
Dhiraj

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

$neha
Guest
$neha

Thank It useful for me 🙂

Anand
Guest
Anand

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.

Othmanebz
Guest
Othmanebz

And for Years ?

Vaishnavi
Guest
Vaishnavi

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

Andrew MacGilvery
Guest
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."); } }

Kiyongs
Guest
Kiyongs

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

Keda87
Guest
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?

Gary
Guest
Gary

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.

CJacobME
Guest
CJacobME

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.

Vidhya
Guest
Vidhya

thank you, code helped me, simple way

srinu
Guest
srinu

good explanation!!!!!!

Mudassir Shahzad
Guest
Mudassir Shahzad

Elegant as ever!

stefanodp
Guest
stefanodp

thanks for the tutorial, it is very clear

Rafal
Guest
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}

Abdul Gafoor
Guest
Abdul Gafoor

Funtastic!!!

Srichandar
Guest
Srichandar

Very clear explanation and comparision…

Marcio
Guest
Marcio

Very good.

Carlos García
Guest
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)

Anand Kumar
Guest
Anand Kumar

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

Valéria Martins
Guest
Valéria Martins

Thanks!! very good!

invalide code
Guest
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)

Selvaram
Guest
Selvaram

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

Radek
Guest
Radek

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 // //--------------------------//… Read more »

Diego Manuel Benitez Enciso
Guest
Diego Manuel Benitez Enciso

excelente tutorial

Surinder
Guest
Surinder

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
Guest
Eliryo

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

Stefan
Guest
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.

guest-AEF6123
Guest
guest-AEF6123

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

Frank Vega
Guest
Frank Vega

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

Frank Vega
Guest
Frank Vega

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.

Rajesh
Guest
Rajesh

Thank you so much…this code really helped…