[英]Joda Time Period print
我想以“ 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秒”; 日子似乎一天都溢出了。 我如何告诉格式化程序忽略溢出,并将溢出内容累加到第一单元中?
这是正确的输出,因为时间段是“ 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.