开发者

Showing period with days, hours, minutes and seconds

I have the following period 1month 5d 22h 35m 39s, which I want to format as 35d 22h 35m 39s. However when using the following formatter the months are just removed and haven't been added to the days:

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .printZeroAlways()
    .appendDays().appendSuffix(" d ")
    .appendHours().appendSuffix(" h ")
    .appendMinutes().appendSuffix(" m ")
    .appendSeconds().appendSuffix(" s ")
    .toFormatter();

After some searching I found that one is supposed to use the normalizedStandard() method on Period, but when using it with period.normalizedStandard(PeriodType.dayTime()) I am getting the following error:

开发者_Python百科
java.lang.UnsupportedOperationException: Field is not supported
    at org.joda.time.PeriodType.setIndexedField(PeriodType.java:690)
    at org.joda.time.Period.withMonths(Period.java:851)
    at org.joda.time.Period.normalizedStandard(Period.java:1541)
    at amadeus.bid.wicket.markup.html.CountDownLabel.onComponentTagBody(CountDownLabel.java:34)

Any ideas?


Like Elijah Cornell sad, in general it makes no sense to convert months to days as months vary in length.

However can imagine an application where it makes sense to plus period to a specific start DateTime (e.g. current time), calc Duration from start to result and convert duration to a period of PeriodType.dayTime():

// 1 month 5d 22h 35m 39s
Period period = new Period(0, 1, 0, 5, 22, 35, 39, 0);

Instant start = new Instant();
// current time => 2011-03-17T22:24:01.848+01:00
Duration dura = new Duration(start, start.toDateTime().plus(period));
Period period2 = new Period(dura).normalizedStandard(PeriodType.dayTime());
// => 36d 21h 35m 39s

Though the result depends on start, its timezone, exceeding daylight saving time boundaries etc., and at this moment doesn't deliver the desired 35d 22h 35m 39s but 36d 21h 35m 39s could this make sense in my opinion because of it is a general use case of Period to plus to an DateTime to yield a new DateTime.


I don't think it will be possible to reliably convert a set number of months in a period back to days because the number of days in a month varies.

Example:

//From: 1month 5d 22h 35m 39s
Period period = new Period(0, 1, 0, 5, 22, 35, 39, 0);
//To: 35d 22h 35m 39s.
period.toStandardDays();

Throws the following exception: java.lang.UnsupportedOperationException: Cannot convert to Days as this period contains months and months vary in length

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜