期间为字符串

57 java period jodatime

我正在使用Java 的Joda-Time库.我在尝试将Period对象转换为"x days,x hours,x minutes"格式的字符串时遇到了一些困难.

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

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

Ste*_*veD 91

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

由ripper234编辑 - 添加TL; DR版本: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()));
}
Run Code Online (Sandbox Code Playgroud)

将打印:

24 minutes and 12 seconds
3 days and 24 minutes and 12 seconds

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

  • 如果你使用gettext我不明白为什么这是难以本地化!+1和ther是一个方法`withLocale(Locale locale)`,它返回一个新的格式化程序,它具有不同的语言环境,用于打印和解析._ (8认同)
  • -1来自我,因为这很难本地化。 (2认同)

sim*_*mao 22

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

Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period))
Run Code Online (Sandbox Code Playgroud)


Jhe*_*ico 12

    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()));
Run Code Online (Sandbox Code Playgroud)

  • 可惜你不能将格式字符串传递给Period或它的Formatter来获得这种效果. (2认同)