开发者

Correctly defining a duration using JodaTime

I've created a method that takes two dates (in milliseconds) and returns a sentence that indicates the duration between these two dates.

For the moment, I have this code:

public static String formatDuration(long start, long end) {
    Interval interval = new Interval(start, end);
    return getPeriodFormatter().print(interval.toPeriod()).trim();
}

private static PeriodFormatter getPeriodFormatter() {
    PeriodFormatter pf = new PeriodFormatterBuilder().printZeroRarelyFirst()
        .appendYears().appendSuffix("y ", "y ")
        .appendMonths().appendSuffix("m" , "m ")
        .appendDays().appendSuffix("d ", "d ")
        .appendHours().appendSu开发者_StackOverflow中文版ffix("h ", "h ")
        .appendMinutes().appendSuffix("m ", "m ")
        .appendSeconds().appendSuffix("s ", "s ")
        .toFormatter();

    return pf;
}

However, I think I misunderstand the way I must define an interval in JodaTime. If I try the following test code:

@Test
public void foobar() {
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
        long start = sdf.parse("10:30:00 24/06/2009").getTime();
        long end = sdf.parse("23:05:17 22/08/2009").getTime();
        System.out.println("Duration: " + formatDuration(start, end));
    } catch (Exception e) {
        e.printStackTrace();
        fail("Could not test duration.");
    }
}

I get the following output, which is wrong (especially on the day part):

Duration: 1m 1d 12h 35m 17s

How do I define the correct duration in JodaTime?


Ok, in fact, what I forgot in my PeriodFormatter is to append the weeks. So if I add the weeks, I get the following output, which is correct:

Duration: 1m 4w 1d 12h 35m 17s

So my question changes a little: Is there a way to display the number of days in month instead of weeks + days? In others words, instead of having:

Duration: 1m 4w 1d 12h 35m 17s

I want to have:

Duration: 1m 29d 12h 35m 17s


Try this.

    Period period = interval.toPeriod( PeriodType.yearMonthDayTime() );

Before formatting the period.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜