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

Jay*_*Jay 2 java jodatime

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

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

Dec*_*eco 11

我不确定你为什么不想指定你需要的东西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()));
Run Code Online (Sandbox Code Playgroud)

产生输出::

1小时1秒

33分20秒

3天9小时31分38秒

  • 当然.. :) 1小时并不总是3600秒,但是,嘿,如果我是一家火箭科学公司,那么我一开始就不会使用JodaTime。 (2认同)