How to calculate date and time difference in Java
In this tutorial, we show you 2 examples to calculate date / time difference in Java :
- Manual time calculation.
- 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
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.
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
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 🙂
How to get Year and month difference too ?
i want to calculate time difference in 12 hour time format, how to do it?
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.
Thank It useful for me 🙂
How to get Year and month difference too ?
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
And for Years ?
good explanation!!!!!!
thank you, code helped me, simple way
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.
Did you consider using the Joda Period object? I think it makes more readable code :
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.
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?
I’ve been using the Joda libraries.
Thanks for the Information with Period.
I like that.
wow, Andrew, your code is great! Joda period looks much better 🙂 Thanks for your code.
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
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
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 ?
The Period contructor and also the method daysBetween want two DateTime parameters, non Date type 🙂
excelente tutorial
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();
}
}
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.
Very simple to calculate days between dates. Probably this is the most reliable site ever..!!! Thanks again..
your code doesnt work for me.
>The method daysBetween(ReadableInstant, ReadableInstant) in the type Days is not applicable for the arguments (Date, Date)
Thanks!! very good!
get your list of date and time questions with sample code in java – http://www.javadiscover.com/search/label/Date%20and%20Time
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)
Very good.
Very clear explanation and comparision…
Funtastic!!!
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}
Thanks for your input of TimeUnit, I think I should updae above article again 🙂
thanks for the tutorial, it is very clear
Elegant as ever!
Nice thanks Alot
Thank you so much…this code really helped…