这个问题已经有一个答案在这里:

我在使用 乔达时 图书馆与Java。我有一些困难,试图把一个时期的对象为一个字符串的格式"x天,x小时,x分钟"。

这些时期对象是第一个通过添加一个量秒钟给他们(他们是化的XML作为秒钟,然后重新从他们)。如果我只是用getHours()等。方法在它们,我得到的是零和的 量秒getSeconds.

我怎么能让乔达计算秒入各自的领域,如天、小时等...?

有帮助吗?

解决方案

你需要恢复正常的时期,因为如果你建造它的总数秒钟,然后这是唯一的价值。正常化,它将把它分成的总天数、分秒,等等。

编辑通过ripper234 -增加一个 TL博士的版本: 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 minutes and 12 seconds
3 days and 24 minutes and 12 seconds

所以你可以看到产出非规范化的时期忽略的小时数(它并没有转换为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();

你失踪的时间,这就是为什么。追加小时后天和问题得到解决。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top