I have the following code that successfully gets me the difference between two days (in days, hours, minutes, seconds):
SimpleDateFormat format = new SimpleD
In Java 9 and later…
Duration.between(
LocalDateTime.parse( "2013-07-31T10:15:01" ) ,
LocalDateTime.parse( "2013-08-01T11:22:33" )
).getDaysPart()
…and…
.getHoursPart()
.getMinutesPart()
.getSecondsPart()
The other Answers are outdated. The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes built into Java.
Period
The Duration class represents a span of time not attached to the timeline as a total number of seconds and nanoseconds. Such a span can be interpreted as a number of days, hours, minutes, and seconds assuming generic 24-hour days and 60-minute hours as no time zone is included.
LocalDateTime start = LocalDateTime.parse( "2013-07-31T10:15:01" );
LocalDateTime stop = LocalDateTime.parse( "2013-08-01T11:22:33" );
Duration d = Duration.between( start , stop );
span: 2013-07-31T10:15:01/2013-08-01T11:22:33
d.toString(): PT25H7M32S
These strings are in standard ISO 8601 formats. The PT25H7M32S
string uses a format of PnYnMnDTnHnMnS where P
marks the beginning and the T
separates the years-months-days from hours-minutes-seconds. The string PT25H7M32S
means “twenty-five hours, seven minutes, and thirty-two seconds”.
See that code live in IdeOne.com.
In Java 9 and later (but not Java 8), these Duration
methods extract each part.
Given a duration of 49H30M20.123S…
toDaysPart()
= 2 toHoursPart()
= 1toMinutesPart()
= 30toSecondsPart()
= 20toMillisPart()
= 123toNanosPart()
= 123000000The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.