我想将时间段格式化为英语和其他语言,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/