繁体   English   中英

使用JodaTime自动将秒数转换为年/日/小时/分钟?

[英]Convert seconds to years/days/hours/minutes automatically, using JodaTime?

如果说x超过3600秒,有没有办法将'x'秒转换为y小时和z秒? 同样,使用JodaTime时,当x超过60但小于3600秒时,将其转换为“a minutes and b seconds”? 我明白我必须在PeriodFormatter中指定我需要的东西,但我不想指定它 - 我想要一个基于秒值的格式化文本。

这与您在论坛上发布的内容类似,然后您的帖子最初将显示为“10秒前发布”... 1分钟后您会看到“发布1分钟20秒前”,同样数周,日,年。

我不确定为什么你不想在PeriodFormatter指定你需要的PeriodFormatter JodaTime不知道您希望如何将字符串显示为字符串,因此您需要通过PeriodFormatter告诉它。

由于3600秒是1小时,正确使用格式化程序将自动为您执行此操作。 这是一个代码示例,在同一格式化程序上使用许多不同的输入,这些输入应该可以达到您想要的结果。

    Seconds s1 = Seconds.seconds(3601);
    Seconds s2 = Seconds.seconds(2000);
    Seconds s3 = Seconds.seconds(898298);
    Period p1 = new Period(s1);
    Period p2 = new Period(s2);
    Period p3 = new Period(s3);

    PeriodFormatter dhm = new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(" and ")
        .appendHours()
        .appendSuffix(" hour", " hours")
        .appendSeparator(" and ")
        .appendMinutes()
        .appendSuffix(" minute", " minutes")
        .appendSeparator(" and ")
        .appendSeconds()
        .appendSuffix(" second", " seconds")
        .toFormatter();

    System.out.println(dhm.print(p1.normalizedStandard()));
    System.out.println(dhm.print(p2.normalizedStandard()));
    System.out.println(dhm.print(p3.normalizedStandard()));

产生输出::

1小时1秒

33分20秒

3天9小时31分38秒

我喜欢上一个答案,但这个选项看起来更具可读性:

PeriodFormat.getDefault().print(new Period(0, 0, yourSecondsValue, 0)
    .normalizedStandard())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM