期间字符串[重复]

Posted

技术标签:

【中文标题】期间字符串[重复]【英文标题】:Period to string [duplicate] 【发布时间】:2010-11-29 06:14:09 【问题描述】:

我在 Java 中使用 Joda-Time 库。我在尝试将 Period 对象转换为“x 天,x 小时,x 分钟”格式的字符串时遇到了一些困难。

这些 Period 对象首先是通过向它们添加一定数量的秒来创建的(它们被序列化为 XML 作为秒,然后从它们重新创建)。如果我只是在其中使用 getHours() 等方法,我得到的只是零,而 total 使用 getSeconds 的秒数。

如何让 Joda 计算各个字段的秒数,例如天数、小时数等...?

【问题讨论】:

相关:***.com/q/10829870/11236 【参考方案1】:

您需要对周期进行标准化,因为如果您使用总秒数来构造它,那么它就是唯一的值。对其进行标准化会将其分解为总天数、分钟数、秒数等。

由 ripper234 编辑 - 添加 TL;DR version: PeriodFormat.getDefault().print(period)

例如:

public static void main(String[] args) 
  PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder()
    .appendDays()
    .appendSuffix(" day", " days")
    .appendSeparator(" and ")
    .appendMinutes()
    .appendSuffix(" minute", " minutes")
    .appendSeparator(" and ")
    .appendSeconds()
    .appendSuffix(" second", " seconds")
    .toFormatter();

  Period period = new Period(72, 24, 12, 0);

  System.out.println(daysHoursMinutes.print(period));
  System.out.println(daysHoursMinutes.print(period.normalizedStandard()));

将打印:

24 分 12 秒
3天24分12秒

因此您可以看到非标准化期间的输出只是忽略了小时数(它没有将 72 小时转换为 3 天)。

【讨论】:

o.O ... 我想我应该更冗长。 感谢您的出色回答。 -1 来自我,因为这很难本地化。 如果你使用 gettext 我不明白为什么这很难本地化! +1 还有一个方法withLocale(Locale locale),它返回一个具有不同区域设置的新格式化程序,用于打印和解析。 我将此答案添加到您自己的答案中,您的答案很好,但对于很多需求来说太冗长了。 ***.com/a/4862467/11236【参考方案2】:

您也可以使用默认格式化程序,这对大多数情况都有好处:

Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period))

【讨论】:

我不会说“大多数情况”,但它很有用,是的。 应该是接受的答案的一部分。 如果您的用户真的关心派系秒数,那么它非常有用。 @dancarter 如果您不想要秒和毫秒,您应该使用正确的 PeriodType 创建 Period。 @benvd 这很有用,谢谢。【参考方案3】:
    Period period = new Period();
    // prints 00:00:00
    System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds()));
    period = period.plusSeconds(60 * 60 * 12);
    // prints 00:00:43200
    System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds()));
    period = period.normalizedStandard();
    // prints 12:00:00
    System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds()));

【讨论】:

遗憾的是,您无法将格式字符串传递给 Period 或其 Formatter 以获得此效果。【参考方案4】:
PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder()
    .appendDays()
    **.appendSuffix(" day", " days")
    .appendSeparator(" and ")
    .appendMinutes()
    .appendSuffix(" minute", " minutes")**
    .appendSeparator(" and ")
    .appendSeconds()
    .appendSuffix(" second", " seconds")
    .toFormatter();

你错过了时间,这就是原因。几天后追加几个小时,问题就解决了。

【讨论】:

以上是关于期间字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章

该插件在激活期间生成了xxx个字符的意外输出[重复]

在where子句期间将十进制转换为日期[重复]

C#将int转换为十六进制[重复]

JSP页面中的UTF-8编码[重复]

避免在 Spark 中解析 json 子字段

复制分配期间的c ++字符串容量更改