1

我想将时间段格式化为英语和其他语言,就像 Joda Time 一样

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

有像Pretty Time这样的库,它们完全符合我的要求,但仅用于与现在比较时间,例如“3 个月前”。我只想要“3个月”。

肯定有一个库可以像 Pretty Time 一样工作,但持续时间是通用的?

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

4

1 回答 1

1

为什么你不能用 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());

也许这不是您想要的,但我希望它有所帮助。

问候。

于 2012-09-25T08:48:11.733 回答