我在使用Joda Time的PeriodFormatter时遇到了麻烦。我想要一个人报告日,小时,分钟和秒钟,但我的尝试似乎在几周之内。我应该做些什么?
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class Problems {
public static void main(String[] args) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroNever()
.appendDays()
.appendSuffix(" day", " days")
.appendSeparator(", ")
.appendHours()
.appendSuffix(" hour", " hours")
.appendSeparator(", ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(", ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
DateTime now = new DateTime();
DateTime justUnderAWeekAgo = now.minusDays(7).plusMinutes(1);
DateTime justOverAWeekAgo = now.minusDays(7).minusMinutes(1);
System.out.println(now);
System.out.println(justUnderAWeekAgo);
System.out.println(justOverAWeekAgo);
// I am happy with the following:
System.out.println(
formatter.print(new Period(justUnderAWeekAgo, now)));
// But not with this (outputs "1 minute" but I want "7 days, 1 minute"):
System.out.println(
formatter.print(new Period(justOverAWeekAgo, now)));
}
}
编辑:我想我可以看到为什么这不起作用 - 即格式化程序只打印Period的各种值,并且由于Periods存储了一个周的值,因此我的日期值为问题期确实是0.但我仍然需要一个很好的方法来做到这一点...
答案 0 :(得分:12)
您的问题是,您不会要求PeriodFormatter
显示周数。
两种可能性:
解决方案1:显示周数:
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroNever()
.appendWeeks()
.appendSuffix(" week", " weeks")
.appendSeparator(", ")
.appendDays()
.appendSuffix(" day", " days")
.appendSeparator(", ")
.appendHours()
.appendSuffix(" hour", " hours")
.appendSeparator(", ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(", ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
示例中的第二个输出将是:
1 week, 1 minute
解决方案2:仅显示日期,因此您必须使用PeriodType.yearMonthDayTime()
:
new Period(justUndeAWeekAgo, now, PeriodType.yearMonthDayTime());
使用第二种解决方案,您可以保持现在的PeriodFormatter
。您的示例中的第二个输出将是:
7 days, 1 minute