期间为字符串 [英] Period to string

查看:114
本文介绍了期间为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the Joda-Time library with Java. I'm having some difficulty trying to turn a Period object to a string in the format of "x days, x hours, x minutes".

这些Period对象是第一个通过向它们添加一些秒来创建它们(它们按秒序列化为XML,然后从它们重新创建)。如果我只是在其中使用getHours()等方法,那么我得到的只有零,并且使用getSeconds的秒数。

These Period objects are first created by adding an amount of seconds to them (they are serialized to XML as seconds and then recreated from them). If I simply use the getHours() etc. methods in them, all I get is zero and the total amount of seconds with getSeconds.

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

How can I make Joda calculate the seconds into the respective fields, like days, hours, etc...?

推荐答案

你需要规范化期间因为如果用总秒数构造它,那么它就是唯一的值。将其标准化会将其分解为总天数,分钟,秒等。

You need to normalize the period because if you construct it with the total number of seconds, then that's the only value it has. Normalizing it will break it down into the total number of days, minutes, seconds, etc.

由ripper234编辑 - 添加 TL; DR版本 PeriodFormat.getDefault()。print(句号)

例如:

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 minutes and 12 seconds



3 days and 24 minutes and 12 seconds

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

So you can see the output for the non-normalized period simply ignores the number of hours (it didn't convert the 72 hours to 3 days).

这篇关于期间为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆