java - 用于在 Java 中 pretty-print 时间段的库,仅提供最重要的字段

标签 java date grails groovy

我想将时间段格式化为英语和其他语言,like Joda Time does .

但是,我想要一种简单的方法来列出一两个最重要的字段,例如“2 年零三个月”或“5 天”,而无需编写代码来处理此问题。 Joda Time 的问题是,除非您编写代码,否则它会给您提供“2 年三个月零五天”之类的输出。

有像 Pretty Time 这样的库这正是我想要的,但只是为了与现在进行比较,比如“3个月前”。我只想要“3个月”。

肯定有一个库的行为类似于 Pretty Time,但适用于通用持续时间?

我专门使用 Grails/Groovy,但普通的 Java 解决方案同样可以接受。

最佳答案

为什么你不能使用 Joda Time 编写一点代码?我遇到了与您类似的问题,我用如下实用方法解决了它:

DateTime dt = new DateTime(); // Now
DateTime plusDuration = dt.plus(new Duration(110376000000L)); // Now plus three years and a half

// Define and calculate the interval of time
Interval interval = new Interval(dt.getMillis(), plusDuration.getMillis());

// Parse the interval to period using the proper PeriodType
Period period = interval.toPeriod(PeriodType.yearMonthDayTime());

// Define the period formatter for pretty printing the period
PeriodFormatter pf = new PeriodFormatterBuilder()
        .appendYears().appendSuffix("y ", "y ")
        .appendMonths().appendSuffix("m", "m ").appendDays()
        .appendSuffix("d ", "d ").appendHours()
        .appendSuffix("h ", "h ").appendMinutes()
        .appendSuffix("m ", "m ").appendSeconds()
        .appendSuffix("s ", "s ").toFormatter();

// Print the period using the previously created period formatter
System.out.println(pf.print(period).trim());

也许这不是您要找的内容,但希望对您有所帮助。

问候。

关于java - 用于在 Java 中 pretty-print 时间段的库,仅提供最重要的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12579194/

相关文章:

java - 未经检查的泛型类类型转换?

企业 Web 应用程序中的 JavaFX - 经典网页的良好替代品?

Android转换月份数组

grails - 从 Controller 传递到 Grails 中的 View

java - 如果语句导致变量无法解析,在语句之外定义变量会导致重复的局部变量吗?

java - 使用 Java 8 从对象列表中查找中值

javascript - 根据 YYYYMMDD 格式的出生日期计算年龄

ios - IOS 中的日期差异

grails - 亲子偷懒获得 child 的身份证

spring - 如何将Grails 2.2.4版本升级到最新或最新版本?