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
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
.
Period is printed in ISO format
The standard ISO format - P yYmMwWd D T hH mMsS.
If you need to find days, hours, minutes and seconds between two days, you should convert period to specific type. Eg:
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));
I think you'll have to format the object of period. Refer this link Period to string
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.