使用JodaTime正确定义持续时间 [英] Correctly defining a duration using JodaTime
问题描述
我创建了一个方法,该方法需要两个日期(以毫秒为单位),并返回一个指示这两个日期之间持续时间的句子.
I've created a method that takes two dates (in milliseconds) and returns a sentence that indicates the duration between these two dates.
目前,我有以下代码:
public static String formatDuration(long start, long end) {
Interval interval = new Interval(start, end);
return getPeriodFormatter().print(interval.toPeriod()).trim();
}
private static PeriodFormatter getPeriodFormatter() {
PeriodFormatter pf = new PeriodFormatterBuilder().printZeroRarelyFirst()
.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();
return pf;
}
但是,我认为我误解了在JodaTime中定义间隔的方式.如果我尝试以下测试代码:
However, I think I misunderstand the way I must define an interval in JodaTime. If I try the following test code:
@Test
public void foobar() {
try {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
long start = sdf.parse("10:30:00 24/06/2009").getTime();
long end = sdf.parse("23:05:17 22/08/2009").getTime();
System.out.println("Duration: " + formatDuration(start, end));
} catch (Exception e) {
e.printStackTrace();
fail("Could not test duration.");
}
}
我得到以下输出,这是错误的(尤其是在白天):
I get the following output, which is wrong (especially on the day part):
Duration: 1m 1d 12h 35m 17s
如何在JodaTime中定义正确的持续时间?
好吧,实际上,我在PeriodFormatter
中忘记的是附加几周.
因此,如果加上周数,则会得到以下输出,这是正确的:
Ok, in fact, what I forgot in my PeriodFormatter
is to append the weeks.
So if I add the weeks, I get the following output, which is correct:
Duration: 1m 4w 1d 12h 35m 17s
所以我的问题有所变化:是否可以显示月份中的天数而不是周数+天数?换句话说,而不是:
So my question changes a little: Is there a way to display the number of days in month instead of weeks + days? In others words, instead of having:
Duration: 1m 4w 1d 12h 35m 17s
我想要拥有:
Duration: 1m 29d 12h 35m 17s
推荐答案
尝试一下.
Period period = interval.toPeriod( PeriodType.yearMonthDayTime() );
在格式化句点之前.
这篇关于使用JodaTime正确定义持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!