一尘不染

如何使用Java计算时间跨度并格式化输出?

java

我想花两次(从纪元以来的秒数),并以如下格式显示两者之间的差异:
- 2 minutes
- 1 hour, 15 minutes
- 3 hours, 9 minutes
- 1 minute ago
- 1 hour, 2 minutes ago

我该怎么做?


阅读 692

收藏
2020-03-17

共1个答案

一尘不染

你也可以使用Joda-Time进行此操作。使用Period代表一个时期。要格式化所需的人表示期间,利用PeriodFormatter它你可以建立PeriodFormatterBuilder

这是一个启动示例:

DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendYears().appendSuffix(" year, ", " years, ")
    .appendMonths().appendSuffix(" month, ", " months, ")
    .appendWeeks().appendSuffix(" week, ", " weeks, ")
    .appendDays().appendSuffix(" day, ", " days, ")
    .appendHours().appendSuffix(" hour, ", " hours, ")
    .appendMinutes().appendSuffix(" minute, ", " minutes, ")
    .appendSeconds().appendSuffix(" second", " seconds")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");

更加简洁明了,不是吗?

现在打印

32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
2020-03-17