Java 以天、小时、分钟和秒显示周期
我有一个月的5d 22h 35m 39s,我想格式化为35d 22h 35m 39s。但是,在使用以下格式化程序时,月份只是被删除,没有添加到天数中:Java 以天、小时、分钟和秒显示周期,java,formatting,jodatime,period,Java,Formatting,Jodatime,Period,我有一个月的5d 22h 35m 39s,我想格式化为35d 22h 35m 39s。但是,在使用以下格式化程序时,月份只是被删除,没有添加到天数中: PeriodFormatter formatter = new PeriodFormatterBuilder() .printZeroAlways() .appendDays().appendSuffix(" d ") .appendHours().appendSuffix(" h ") .appendMinute
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways()
.appendDays().appendSuffix(" d ")
.appendHours().appendSuffix(" h ")
.appendMinutes().appendSuffix(" m ")
.appendSeconds().appendSuffix(" s ")
.toFormatter();
经过一些搜索后,我发现应该在Period上使用normalizedStandard()方法,但是当与Period.normalizedStandard(PeriodType.day())
一起使用时,我得到以下错误:
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)
有什么想法吗?我认为不可能可靠地将一段时间内固定的月份数转换回天数,因为一个月内的天数是不同的 例如:
//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:无法转换为天,因为此期间包含月,且月的长度不同与Elijah Cornell sad类似,通常情况下,将月转换为天是没有意义的,因为月的长度不同
但是,您可以想象这样一个应用程序,在该应用程序中,将时段添加到特定的开始时间DateTime
(例如当前时间),计算从开始到结果的持续时间Duration
,并将持续时间转换为PeriodType.day()的时段:
虽然结果取决于启动、时区、超过夏令时界限等。,在我看来,这是否有意义呢?因为这是一个通用的用例,将Period
加上DateTime
,生成一个新的DateTime
,可能有助于你使用相同的后缀几个月和几分钟。吉尔伯特:很抱歉,我想删除它。谢谢你的回复。从用户的角度来看,我认为显示日期而不是月份是有意义的。一个系统应该更好地计算,而不是把计算留给用户。我试图理解在你上面的例子中发生了什么。为什么它不能提供所需的功能?@kristofer让我们开始简化Instant start=new Instant(“2011-03-17T00:00:00.000+01:00”)代码>。然后start.toDateTime().plus(period)
变为2011-04-22T22:35:39.000+02:00
,因为04
是03
之后的1个月,22
是17
之后的5天,22:35:39
是。。。在00:00:00
之后。但是1。如果您从2011-03-17
到2011-04-22
计算,您将获得36天。二,。缺少的小时数是将时钟从2011-03-27
从02:00
提前到03:00
(夏令时开始),您可以在将utc时区偏差从+01:00
更改为+02:00
时看到这一点。@kristofer,如果您改为从即时开始=新即时开始(“2011-04-01T00:00:00.000+02:00”);
在夏令时内,如果您的月长为30天(4月),您将得到所需的35d 22h 35m 39s
。结论:这取决于文章中已经提到的开始时间。
// 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