【问题标题】:Showing period with days, hours, minutes and seconds以天、小时、分钟和秒显示周期
【发布时间】:2011-03-18 05:48:26
【问题描述】:

我有以下时间段 1month 5d 22h 35m 39s,我想将其格式化为 35d 22h 35m 39s。但是,当使用以下格式化程序时,月份只是被删除并且没有被添加到天数中:

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

经过一番搜索,我发现应该在 Period 上使用 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)

有什么想法吗?

【问题讨论】:

标签: java formatting jodatime period


【解决方案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 39s36d 21h 35m 39s我的观点是因为它是Period 的一般用例,加上DateTime 以产生新的DateTime

【讨论】:

  • 感谢您的回复。从用户的角度来看,我实际上认为显示日期而不是月份是有意义的。系统应该更好地计算而不是将其留给用户。我试图了解您上面的示例中发生了什么。为什么它没有达到预期的效果?
  • @Kristoffer 让我们从Instant start = new Instant("2011-03-17T00:00:00.000+01:00"); 开始简化。然后start.toDateTime().plus(period) 变为2011-04-22T22:35:39.000+02:00,因为0403 之后的1 个月,2217 之后的5 天,而22:35:39 是...在00:00:00 之后。但是 1. 如果你从 2011-03-17 数到 2011-04-22 你得到 36 天。并且 2. 缺少的时间是从将时钟在 2011-03-2702:0003:00 (夏令时的开始),您可以在将 utc 时区偏差从 +01:00 更改为 +02:00 时看到。
  • @Kristoffer 如果您在夏令时内以 Instant start = new Instant("2011-04-01T00:00:00.000+02:00"); 开始,并且一个月(4 月)有 30 天,您会得到想要的 35d 22h 35m 39s。结论:这取决于帖子中已经提到的开始时间。
【解决方案2】:

我认为不可能将一段时间内的固定月数可靠地转换回天数,因为一个月中的天数会有所不同。

例子:

//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: 无法转换为天,因为此期间包含月份且月份长度不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多