字符串的句点 [英] Period to string

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

问题描述

我在 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天全站免登陆