期间到string

我正在使用Java的Joda-Time库。 我有一些困难,试图将一个Period对象转换为“x天,x小时,x分钟”格式的string。

这些Period对象首先通过向它们添加一定的秒数来创build(它们以秒为序列化为XML,然后从中重新创build)。 如果我只是简单地使用getHours()等方法,我所得到的就是零和getSeconds的秒数。

我怎样才能让乔达计算各个领域的秒数,如天,小时等…?

你需要规范期限,因为如果你用秒的总数来构造它,那么这就是它唯一的价值。 正常化将分解成总天数,分钟,秒等

由ripper234编辑 – 添加TL; DR版本 : PeriodFormat.getDefault().print(period)

例如:

 public static void main(String[] args) { PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder() .appendDays() .appendSuffix(" day", " days") .appendSeparator(" and ") .appendMinutes() .appendSuffix(" minute", " minutes") .appendSeparator(" and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); Period period = new Period(72, 24, 12, 0); System.out.println(daysHoursMinutes.print(period)); System.out.println(daysHoursMinutes.print(period.normalizedStandard())); } 

将打印:

  24分钟和12秒 
  3天24分12秒 

因此,您可以看到非标准化期间的输出忽略了小时数(它没有将72小时转换为3天)。

您也可以使用默认格式化程序,这对于大多数情况非常有用:

 Period period = new Period(startDate, endDate); System.out.println(PeriodFormat.getDefault().print(period)) 
  Period period = new Period(); // prints 00:00:00 System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds())); period = period.plusSeconds(60 * 60 * 12); // prints 00:00:43200 System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds())); period = period.normalizedStandard(); // prints 12:00:00 System.out.println(String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds())); 
 PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder() .appendDays() **.appendSuffix(" day", " days") .appendSeparator(" and ") .appendMinutes() .appendSuffix(" minute", " minutes")** .appendSeparator(" and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); 

你错过了几个小时,这就是为什么。 追加数小时后问题解决。