2016-09-20 55 views
0

我有一個格式如下:喬達時間PeriodFormatter不打印多年

private static PeriodFormatter formatter = new PeriodFormatterBuilder() 
      .printZeroNever() 
      .appendYears().appendSuffix(" years ") 
      .appendMonths().appendSuffix(" months ") 
      .appendWeeks().appendSuffix(" weeks ") 
      .appendDays().appendSuffix(" days ") 
      .appendHours().appendSuffix(" hours ") 
      .appendMinutes().appendSuffix(" minutes ") 
      .appendSeconds().appendSuffix(" seconds") 
      .toFormatter(); 

和如下使用它:

 DateTime dt = DateTime.parse("2010-06-30T01:20"); 
     Duration duration = new Duration(dt.toInstant().getMillis(), System.currentTimeMillis()); 

     Period period = duration.toPeriod().normalizedStandard(PeriodType.yearMonthDayTime()); 
     formatter.print(period); 

輸出爲:

2274 days 13 hours 59 minutes 39 seconds 

那麼,是幾年?

回答

1

這裏的根本問題是您使用Duration來開始IMO。 A Duration只是毫秒數......考慮到年數,有些麻煩,因爲一年365或366天(甚至取決於日曆系統)。這就是爲什麼toPeriod method you're calling明確表示:

只有期間類型中的精確字段將被使用。因此,只能使用該時段的小時,分​​鍾,秒和毫秒字段。年,月,周和日期字段將不會填充。

然後你打電話normalizedStandard(PeriodType)其中包括:

的日子場和下面將被標準化爲必要的,但是這不會溢出到幾個月領域。因此,1年15個月的時間將正常化爲2年3個月。但1個月40天的期限將保留爲1個月40天。

不像從一個Duration創建期間,直接從DateTime創建它和「現在」,例如

DateTime dt = DateTime.parse("2010-06-30T01:20"); 
DateTime now = DateTime.now(); // Ideally use a clock abstraction for testability 
Period period = new Period(dt, now, PeriodType.yearMonthDayTime());