4

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:902 mins:4 seconds:0 00:902:04:00

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
fphilip
  • 159
  • 1
  • 8
  • This is a duplicate of http://stackoverflow.com/questions/1440557/joda-time-period-to-string – ditkin May 07 '11 at 12:50

2 Answers2

1

The chronology that you are using may not consider days to be precise. Instead of GregorianChronology, try using IOSChronology.getInstanceUTC().

Nathan Ryan
  • 12,893
  • 4
  • 26
  • 37
1

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.

ditkin
  • 6,774
  • 1
  • 35
  • 37