I want to subtract two time periods say 16:00:00 from 19:00:00. Is there any Java function for this? The results can be in milliseconds, seconds, or minutes.
-
5probably http://joda-time.sourceforge.net/ – stacker Feb 07 '11 at 23:23
19 Answers
Java 8 has a cleaner solution - Instant and Duration
Example:
import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

- 14,756
- 10
- 70
- 125

- 1,871
- 1
- 9
- 2
-
-
So this boils down to two imports and `System.out.println("Duration: " + String.valueOf(Duration.between(outerstart, Instant.now()).toMillis()));` to log the duration. I wouldn't call that a nice and clean solution in Java8 if other languages can do it with code like `print("Duration: " + str(time.time()-start))`... – Luc Feb 06 '19 at 17:53
-
10@Luc cleanliness isn't the same as brevity. It's much clearer exactly what is happening in the Java 8 version, and it's also much easier to tweak if, for example, you want to report the duration between two instants in a unit other than milliseconds, or as multiple units (e.g. `1h 15m 3.022s` instead of `4503022 milliseconds`). – JakeRobb Nov 01 '19 at 20:07
String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Difference is in milliseconds.
I modified sfaizs post.
-
7
-
Inverting the variables won't do much good.. In this example, sure, you could invert them and take the absolute value or something. But what happens if you have midnight (00:00)? – rj2700 Feb 20 '17 at 23:00
-
1
-
what about the difference between 08:00:00 today and yesterday's 10:00:00??????? I don't think what you suggested is a breakable logic. – channae Mar 20 '18 at 12:14
-
I want to get the minutes between 2 Dates (time) and them don't have the midnight bcz my range times from 05h00m to 22h00m, so your answer helped me. Thanks bro! – Nghien Nghien Apr 07 '23 at 04:27
To get pretty timing differences, then
// d1, d2 are dates
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.");

- 30,738
- 21
- 105
- 131

- 88,237
- 28
- 143
- 153
-
-
-
@PeterMortensen I mean time difference in the human-readable format like "2 days 3 hours 13 mins". – Fizer Khan Sep 11 '21 at 13:50
Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);
long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();

- 1,866
- 22
- 17
-
1This is also available for Java SE 6 and 7 as a [back port](https://github.com/ThreeTen/threetenbp), as well as for [Android](https://github.com/JakeWharton/ThreeTenABP). – Bryan Aug 24 '16 at 14:34
Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.
Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)

- 27,509
- 17
- 111
- 155
import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds.
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.
and, to show in a nicer format, you can use:
DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));

- 2,892
- 3
- 31
- 44
-
2This duplicates another answer and adds no new content. Please don't post an answer unless you actually have something new to contribute. – DavidPostill Mar 21 '15 at 06:19
-
@DavidPostill, thank you for your heads up. But the solution I needed myself and didn't find in the GENESIS's post was the time difference between the execution of two lines of code (like the starting point and ending point of program or before and after running a method, not some static times). I thought this may help. – Alisa Mar 21 '15 at 17:00
Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.
Advanced Java 8 libraries. ChronoUnit for Differences.
ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.
LocalTime one = LocalTime.of(5,15);
LocalTime two = LocalTime.of(6,30);
LocalDate date = LocalDate.of(2019, 1, 29);
System.out.println(ChronoUnit.HOURS.between(one, two)); //1
System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
First example shows that between truncates rather than rounds.
The second shows how easy it is to count different units.
And the last example reminds us that we should not mess up with dates and times in Java :)

- 456
- 7
- 14
I found this cleaner.
Date start = new Date();
//Waiting for 10 seconds
Thread.sleep(10000);
Date end = new Date();
long diff = end.getTime() - start.getTime();
String TimeTaken = String.format("[%s] hours : [%s] mins : [%s] secs",
Long.toString(TimeUnit.MILLISECONDS.toHours(diff)),
TimeUnit.MILLISECONDS.toMinutes(diff),
TimeUnit.MILLISECONDS.toSeconds(diff));
System.out.println(String.format("Time taken %s", TimeTaken));
Output
Time taken [0] hours : [0] mins : [10] secs

- 30,738
- 21
- 105
- 131

- 1,396
- 12
- 27
public class timeDifference {
public static void main(String[] args) {
try {
Date startTime = Calendar.getInstance().getTime();
Thread.sleep(10000);
Date endTime = Calendar.getInstance().getTime();
long difference = endTime.getTime() - startTime.getTime();
long differenceSeconds = difference / 1000 % 60;
long differenceMinutes = difference / (60 * 1000) % 60;
long differenceHours = difference / (60 * 60 * 1000) % 24;
long differenceDays = difference / (24 * 60 * 60 * 1000);
System.out.println(differenceDays + " days, ");
System.out.println(differenceHours + " hours, ");
System.out.println(differenceMinutes + " minutes, ");
System.out.println(differenceSeconds + " seconds.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}

- 30,738
- 21
- 105
- 131

- 169
- 2
- 8
String start = "12:00:00";
String end = "02:05:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(start);
Date date2 = format.parse(end);
long difference = date2.getTime() - date1.getTime();
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);
if(minutes<0)minutes += 1440;
Now minutes will be the correct duration between two time (in minute).

- 5,266
- 23
- 39
- 56
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
String time1 = "12:00:00";
String time2 = "12:01:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference/1000);
}
}
It throws exception handles parsing exceptions.

- 30,738
- 21
- 105
- 131
-
Re *"It throws exception handles parsing exceptions."*: That is close to incomprehensible. Can you [rephrase your answer](https://stackoverflow.com/posts/45443155/edit)? (But ***without*** "Edit:", "Update:", or similar - the question/answer should appear as if it was written today.) – Peter Mortensen Sep 07 '21 at 15:04
The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use JodaTime.

- 29,539
- 13
- 92
- 123
-
1I never mentioned unix timestamps. Also it is a well known fact that the Java Date and Time API sucks for more than occassional use. JodaTime is much better and probably the way to go until JSR 310 is part of Java. http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen – Manfred Moser Feb 07 '11 at 23:28
-
@Manfred Moser: may you should have... Both the default Java time classes and Joda give a time in millis that start from what is called the **Unix** epoch. At this point they become darn close to **Unix** timestamps (one being in millis, the other in seconds). In any case what the OP wants can be done trivially using the default Java classes, taking the number of millis since the **Unix** epoch and substracting them. – SyntaxT3rr0r Feb 08 '11 at 00:00
-
1Sure it can be done trivially. And if you do lots of date and time calculations in your app you can also trivially create lots of bugs yourself and reinvent your own little library implementing parts of JodaTime yourself again. For one simple calculation that might be okay but for frequent use it is worth using a decent library. I am just trying point out that the first simple solution might not be leading you on the best path. Whats wrong with that? – Manfred Moser Feb 08 '11 at 05:21
-
3@Manfred Moser: Actually, the first simple solution *is* the right path, considering the OP asked for the difference between two time periods, not changes in an atomic clock :) – Christian Feb 08 '11 at 21:55
-
Sure.. for this example and specific question only. Not for the bigger picture though. – Manfred Moser Feb 08 '11 at 22:04
This can be easily done using Java 8 LocalTime;
String time1 = "16:00:00";
String time2 = "19:00:00";
long seconds = Duration.between(LocalTime.parse(time1), LocalTime.parse(time2)).getSeconds()
Duration also supports toMillis(), toMinutes() which can be used in place of getSeconds() to get milliseconds or minutes

- 71,965
- 6
- 74
- 110

- 785
- 8
- 13
-
Can you link to (official) documentation? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today. And *not* using naked links.) – Peter Mortensen Sep 07 '21 at 15:08
Аlternative option if time from different days is taken, for example: 22:00 and 01:55.
public static long getDiffTime(Date date1, Date date2){
if (date2.getTime() - date1.getTime() < 0) {// if for example date1 = 22:00, date2 = 01:55.
Calendar c = Calendar.getInstance();
c.setTime(date2);
c.add(Calendar.DATE, 1);
date2 = c.getTime();
} //else for example date1 = 01:55, date2 = 03:55.
long ms = date2.getTime() - date1.getTime();
//235 minutes ~ 4 hours for (22:00 -- 01:55).
//120 minutes ~ 2 hours for (01:55 -- 03:55).
return TimeUnit.MINUTES.convert(ms, TimeUnit.MILLISECONDS);
}

- 75
- 2
- 8
Try this:
public String timeDifference8(String startTime, String endTime) {
LocalTime initialTime = LocalTime.parse(startTime);
LocalTime finalTime =LocalTime.parse(endTime);
StringJoiner joiner = new StringJoiner(":");
long hours = initialTime.until( finalTime, ChronoUnit.HOURS);
initialTime = initialTime.plusHours( hours );
long minutes = initialTime.until(finalTime, ChronoUnit.MINUTES);
initialTime = initialTime.plusMinutes( minutes );
long seconds = initialTime.until( finalTime, ChronoUnit.SECONDS);
joiner.add(String.valueOf(hours));
joiner.add(String.valueOf(minutes));
joiner.add(String.valueOf(seconds));
return joiner.toString();
}

- 2,917
- 23
- 46
- 68

- 11
- 1
-
Re *"Try this"*: An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/54307110/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 07 '21 at 15:05
import java.sql.*;
class Time3 {
public static void main(String args[]){
String time1 = "01:03:23";
String time2 = "02:32:00";
long difference ;
Time t1 = Time.valueOf(time1);
Time t2 = Time.valueOf(time2);
if(t2.getTime() >= t1.getTime()){
difference = t2.getTime() - t1.getTime() -19800000;
}
else{
difference = t1.getTime() - t2.getTime() -19800000;
}
java.sql.Time time = new java.sql.Time(difference);
System.out.println(time);
}
}

- 1,662
- 18
- 29

- 41
- 5
/*
* Total time calculation.
*/
private void getTotalHours() {
try {
// TODO Auto-generated method stub
if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
Long min1 = tfTimeOut.getMinutesValue();
Long min2 = tfTimeIn.getMinutesValue();
Long hr1 = tfTimeOut.getHoursValue();
Long hr2 = tfTimeIn.getHoursValue();
Long hrsTotal = new Long("0");
Long minTotal = new Long("0");
if ((hr2 - hr1) == 1) {
hrsTotal = (long) 1;
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
hrsTotal++;
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) > 0) {
hrsTotal = (hr2 - hr1);
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) == 0) {
if (min1 != 0 || min2 != 0) {
if (min2 > min1) {
hrsTotal = (long) 0;
minTotal = min2 - min1;
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
}
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
String hrsTotalString = hrsTotal.toString();
String minTotalString = minTotal.toString();
if (hrsTotalString.trim().length() == 1) {
hrsTotalString = "0" + hrsTotalString;
}
if (minTotalString.trim().length() == 1) {
minTotalString = "0" + minTotalString;
}
tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
} else {
tfTotalTime.setValue("00.00");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
-
3While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value. – Benjamin W. Apr 08 '16 at 04:02
class TimeCalculator
{
String updateTime;
public TimeCalculator(String time)
{
// Time should be in 24 hours format like 15/06/2016 17:39:20
this.updateTime = time;
}
public String getTimeDifference()
{
String td = null;
// Get Current Time
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date currentDate = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);
int c_year = calendar.get(Calendar.YEAR);
int c_month = calendar.get(Calendar.MONTH) + 1;
int c_day = calendar.get(Calendar.DAY_OF_MONTH);
// Get Editing Time
Date edit_date = sdf.parse(updateTime);
Calendar edit_calendar = new GregorianCalendar();
edit_calendar.setTime(edit_date);
int e_year = edit_calendar.get(Calendar.YEAR);
int e_month = edit_calendar.get(Calendar.MONTH) + 1;
int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);
if(e_year == c_year && e_month == c_month && e_day == c_day)
{
int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
int c_minutes = calendar.get(Calendar.MINUTE);
int c_seconds = calendar.get(Calendar.SECOND);
int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
int e_minutes = edit_calendar.get(Calendar.MINUTE);
int e_seconds = edit_calendar.get(Calendar.SECOND);
if(c_hours == e_hours && c_minutes == e_minutes && c_seconds == e_seconds)
{
td = "just now";
return td;
}
else if(c_hours == e_hours && c_minutes == e_minutes)
{
int d_seconds = c_seconds-e_seconds;
td = String.valueOf(d_seconds);
td = td + " seconds ago";
return td;
}
else if(c_hours == e_hours && c_minutes != e_minutes)
{
int d_minutes = c_minutes-e_minutes;
int d_seconds;
if(c_seconds>e_seconds)
{
d_seconds = c_seconds-e_seconds;
}
else
{
d_seconds = e_seconds-c_seconds;
}
td = "00:" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
else
{
int d_minutes, d_seconds, d_hours;
d_hours = c_hours-e_hours;
if(c_minutes>e_minutes)
{
d_minutes = c_minutes - e_minutes;
}
else
{
d_minutes = e_minutes - c_minutes;
}
if(c_seconds>e_seconds)
{
d_seconds = c_seconds - e_seconds;
}
else
{
d_seconds = e_seconds - c_seconds;
}
td = String.valueOf(d_hours) + ":" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
}
else if(e_year == c_year && e_month == c_month && c_day == e_day+1)
{
td = "yesterday";
return td;
}
else
{
td = updateTime;
return td;
}
}
}

- 30,738
- 21
- 105
- 131
using Instant
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-04T11:35:31.00Z");
long duration = Duration.between(start, end).toMillis();
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)*60;
String time = String.format("%02d hours, %02d min, %02d sec",
TimeUnit.MILLISECONDS.toHours(duration),
TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.MILLISECONDS.toHours(duration) * 60,
TimeUnit.MILLISECONDS.toSeconds(duration) - minutes);
;
System.out.println("time = " + time);

- 12,337
- 16
- 79
- 126