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

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

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

我不确定为什么你不想在PeriodFormatter指定你需要的PeriodFormatterJodaTime不知道您希望如何将字符串显示为字符串,因此您需要通过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())