I have a problem with jodatime api. I can't understand why this test doesn't works. I need resolve how many days, hours, mins and seconds I have in X milliseconds. But the days value aren't resolved.... any idea?
@Test
public void testTime() {
long secs = 3866 * 24 * 35;
long msecs = secs * 1000;
//Period period = duration.toPeriod();
PeriodType periodType = PeriodType.forFields(
new DurationFieldType[]{
DurationFieldType.days(),
DurationFieldType.hours(),
DurationFieldType.minutes(),
DurationFieldType.seconds(),
});
Duration duration = Duration.standardSeconds(secs);
Period period = duration.toPeriod(periodType, GregorianChronology.getInstance());
System.out.println("days:" + period.getDays());
System.out.println("hours:" + period.getHours());
System.out.println("mins:" + period.getMinutes());
System.out.println("seconds:" + period.getSeconds());
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendDays()
.appendSeparator(":")
.appendHours()
.appendSeparator(":")
.appendMinutes()
.appendSeparator(":")
.appendSecondsWithOptionalMillis()
.toFormatter();
StringBuffer stringBuffer = new StringBuffer();
periodFormatter.printTo(stringBuffer, period);
System.out.println(">>>" + stringBuffer);
}
the output is days:0 hours开发者_如何学Go:902 mins:4 seconds:0 00:902:04:00
You need to normalize the period using:
Period normalizedPeriod = period.normalizeStandard();
or
Period normalizedPeriod = period.normalizeStandardPeriodType();
Then you can use the normalizedPeriod and see the results you are looking for. As a quick test I modified your junit test case and added the line:
period = period.normalizedStandard();
right after your create the period from the duration.
The chronology that you are using may not consider days to be precise. Instead of GregorianChronology, try using IOSChronology.getInstanceUTC()
.
精彩评论