我想以“2天,3小时,5分钟和8秒”的形式打印两个日期之间的差异。
我正在使用此代码调用Joda-Time库,但我遇到了一些麻烦。
Calendar cal = Calendar.getInstance();
DateTime firstSeen = new DateTime(cal.getTime());
cal.add(Calendar.HOUR, 24*8);
cal.add(Calendar.MINUTE, 10);
cal.add(Calendar.SECOND, 45);
DateTime lastSeen = new DateTime(cal.getTime());
Period period = new Period(firstSeen, lastSeen);
PeriodFormatter daysHoursMinutesSeconds = new PeriodFormatterBuilder()
.appendDays()
.appendSuffix(" day", " days")
.appendSeparator(", ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
String periodFormatted;
periodFormatted = daysHoursMinutesSeconds.print(period);
System.out.println(periodFormatted);
应该打印的是“8天10分45秒”。相反,我得到“1天,10分45秒”;这一天似乎已经过了一周。如何告诉格式化程序忽略溢出并总结溢出到第一个单元的内容?
答案 0 :(得分:2)
这是正确的输出,因为期间为“1周1天45分钟”且周字段未打印:
package com.stackoverflow.so21002436;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class App {
public static void main(final String[] args)
{
final DateTime firstSeen = DateTime.now();
final DateTime lastSeen = firstSeen.plusDays(8).plusMinutes(10).plusSeconds(45);
final Period period = new Period(firstSeen, lastSeen);
System.err.println(period); // P1W1DT10M45S, ie. 1 day, 10 minutes and 45 seconds
final PeriodFormatter daysHoursMinutesSeconds = new PeriodFormatterBuilder().appendDays()
.appendSuffix(" day", " days")
.appendSeparator(", ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
final String periodFormatted = daysHoursMinutesSeconds.print(period);
System.out.println(periodFormatted);
}
}
或使用特定的PeriodType
:
package com.stackoverflow.so21002436;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class App {
public static void main(final String[] args)
{
final DateTime firstSeen = DateTime.now();
final DateTime lastSeen = firstSeen.plusDays(8).plusMinutes(10).plusSeconds(45);
final Period period = new Period(firstSeen, lastSeen, PeriodType.dayTime());
System.err.println(period); // P8DT10M45S, ie. 8 days, 10 minutes and 45 seconds
final PeriodFormatter daysHoursMinutesSeconds = new PeriodFormatterBuilder().appendDays()
.appendSuffix(" day", " days")
.appendSeparator(", ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
final String periodFormatted = daysHoursMinutesSeconds.print(period);
System.out.println(periodFormatted);
}
}