Reputation: 3104
I am trying to find the days, hours, minutes and seconds between two date/times. I thought I could use period and I tried the code below but I get a non nonsensical answer.
DateTime dt1 = new DateTime("2004-12-13T21:39:45.618-06:00");
DateTime dt2 = new DateTime("2004-12-13T21:39:45.618-08:00");
Period p = new Period(dt1, dt2);
System.out.println("Test: " + p);
From this I get output:
I/System.out: Test: PT2H
Not sure what this is meant to mean.
Thanks for your help
Upvotes: 1
Views: 4503
Reputation: 29693
Period is printed in ISO format
The standard ISO format - PyYmMwWdDThHmMsS.
If you need to find days, hours, minutes and seconds between two days, you should convert period to specific type. E.g.:
Period p = new Period(dt1, dt2);
System.out.println("Days: " + p.toStandardDays().getDays());
System.out.println("Hours: " + p.toStandardHours().getHours());
System.out.println("Minutes: " + p.toStandardMinutes().getMinutes());
System.out.println("Seconds: " + p.toStandardSeconds().getSeconds());
or use special static methods in classes Days
, Hours
, Minutes
and Seconds
System.out.println("Days: " + Days.daysBetween(dt1, dt2));
System.out.println("Hours: " + Hours.hoursBetween(dt1, dt2));
System.out.println("Minutes: " + Minutes.minutesBetween(dt1, dt2));
System.out.println("Seconds: " + Seconds.secondsBetween(dt1, dt2));
Upvotes: 2
Reputation: 18507
toString()
method in Period
gives you the value as ISO8601 duration format.
From the API:
Gets the value as a String in the style of the ISO8601 duration format. Technically, the output can breach the ISO specification as weeks may be included. For example, "PT6H3M5S" represents 6 hours, 3 minutes, 5 seconds.
As you ask to get separately the days,hours,minutes and seconds you can use the convenient get
methods from the API:
import org.joda.time.DateTime;
import org.joda.time.Period;
...
DateTime dt1 = new DateTime("2004-12-13T21:39:45.618-06:00");
DateTime dt2 = new DateTime("2004-12-13T21:39:45.618-08:00");
Period p = new Period(dt1, dt2);
System.out.println("DAYS: " + p.getDays())
System.out.println("HOURS: " + p.getHours());
System.out.println("MINUTES: " + p.getMinutes());
System.out.println("SECONDS: " + p.getSeconds());
Or alternatively as other answers suggests use PeriodFormatter
.
Upvotes: 6
Reputation: 27971
You need to format your Period
. A simple way is to use the default one like this:
PeriodFormat.getDefault().print(period)
You can also create your own format with PeriodFormatter
.
Upvotes: 1
Reputation: 111
I think you'll have to format the object of period. Refer this link Period to string
Upvotes: 1