2010-11-10 110 views
2

我有以下期间1个月5天22小时35分39秒,我想要格式化为35天22小时35分39秒。使用以下格式,月份刚刚删除,并没有被添加到天然而,当:显示天数,小时,分钟和秒数

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

经过一番搜索,我发现一个应该使用normalizedStandard()方法的时期,但在使用它与period.normalizedStandard(PeriodType.dayTime())我收到以下错误:

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) 

任何想法?

+0

也许thsi帮助http://stackoverflow.com/questions/1440557/joda-time-period-to-string – Thariama 2010-11-10 13:42:08

+0

您使用的月份和分钟相同的后缀。 – 2010-11-10 14:04:10

+0

吉尔伯特:抱歉意味着要删除它。 – Kristoffer 2010-11-15 07:35:20

回答

0

我不认为有可能将某个月份的某个月数转换回几天,因为一个月中的天数会有所不同。

例子:

//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(); 

抛出以下异常:java.lang.UnsupportedOperationException:因为这期间包含了几个月的时间长短不一

1

以利亚一样康奈尔伤心,一般无法转换为天随着月份的长度变化,将月份转换为日期是没有意义的。

然而可以想象其中是有意义的应用程序加上周期到一个特定的开始DateTime(例如当前时间),计算值Duration从开始到产生和转换持续时间,以一个周期的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 

虽然结果取决于开始,它的时区,超过夏令时边界等,并且此时不提供期望的35d 22h 35m 39s,但是36d 21h 35m 39s这对我而言可能是有意义的,因为它是Period的一般用例加上DateTime产生新的DateTime

+0

感谢您的回复。从用户的角度来看,我认为显示日期而不是几个月是有意义的。系统应该更好地计算,而不是将其留给用户。 我试图了解上面例子中发生了什么。为什么它没有提供所需的? – Kristoffer 2011-03-18 09:16:36

+0

@Kristoffer让我们开始使用'Instant start = new Instant(“2011-03-17T00:00:00.000 + 01:00”);''来简化。然后''start.toDateTime()。plus(句点)'由于'04'在'03'后1个月变成'2011-04-22T22:35:39.000 + 02:00','22'在' 17:和22:35:39'是...... 00:00:00之后。但是1.如果你从“2011-03-17”到“2011-04-22”,你会得到36天。 2.错过的时间是从'02:00'到'03:00'(夏令时开始)'2011-03-27'的时钟提前,您可以在将utc时区偏差从' +01:00'到'+02:00'。 – binuWADa 2011-03-19 13:37:10

+0

@Kristoffer如果你用'Instant start = new Instant(“2011-04-01T00:00:00.000 + 02:00”)开始,'在夏令时内,并且有30天长的月份(4月) '35d 22h 35m 39s'。结论:这取决于邮政已经提到的开始时间。 – binuWADa 2011-03-19 13:39:49

相关问题