I have two objects of DateTime, which need to find the duration of their difference,
I have the following code but not sure how to continue it to get to the expected results as following:
Example
11/03/14 09:30:58
11/03/14 09:33:43
elapsed time is 02 minutes and 45 seconds
-----------------------------------------------------
11/03/14 09:30:58
11/03/15 09:30:58
elapsed time is a day
-----------------------------------------------------
11/03/14 09:30:58
11/03/16 09:30:58
elapsed time is two days
-----------------------------------------------------
11/03/14 09:30:58
11/03/16 09:35:58
elapsed time is two days and 05 mintues
Code
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
Here is how the problem can solved in Java 8 just like the answer by shamimz.
Source : http://docs.oracle.com/javase/tutorial/datetime/iso/period.html
The code produces output similar to the following:
We have to use LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get hour,minute,second differences.
The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides utility methods to do that:
In Java 8, you can make of
DateTimeFormatter
,Duration
, andLocalDateTime
. Here is an example:try the following
This is a program I wrote, which gets the number of days between 2 dates(no time here).
http://pastebin.com/HRsjTtUf