2016-10-18 47 views
0

我試圖計算日期之間的差異,比如天前,分鐘前,兩個月前,...喬達時間period.getMonths()始終爲0

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
     "dd/M/yyyy HH:mm:ss"); 

Date now = null; 
try { 
    now = simpleDateFormat.parse(simpleDateFormat.format(new Date())); 
} catch (ParseException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
Date time = null; 
try { 
    time = simpleDateFormat.parse(simpleDateFormat.format(timestamp)); 
} catch (ParseException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

Interval interval = new Interval(time.getTime(), now.getTime()); 
Period period = interval.toPeriod(); 

Integer s = period.getSeconds(); 
Integer m = period.getMinutes(); 
Integer h = period.getHours(); 
Integer days = period.getDays(); 

Integer mo = period.getMonths(); 
Integer y = period.getYears(); 

Integer mo = period.getMonths();始終爲零

i/p=> now =Tue Oct 18 12:15:50 IST 2016 
     time=Mon Sep 26 14:38:36 IST 2016 

o/p=> s=14 
     m=37 
     h=21 
     days=0 
     mo=0 
     y=0 

我也試過LocalDateDateTime但有同樣的問題。

+3

'simpleDateFormat.parse(simpleDateFormat.format(x))'是什麼點? – Andreas

+1

你的約會距離不到一個月,所以你幾個月得到'0'這個事實並不令人驚訝。但是,天應該不爲零。如果您使用Java 8,則會有一個新的內置日期/時間庫(由執行JodaTime的人員創建),其中包括一個新的格式化程序/解析器。 –

+0

因爲是3周,所以你得到了0天。 'period.getWeeks()'返回3.您可以很容易地找到與我一樣的方式,只需打印期間:'P3WT21H37M14S' – Andreas

回答

2

你現在正在這樣做,你會得到一個以周爲單位的週期。期間的「周」字段將被設置,但年/月/日字段不會被設置。

如果你想用年,月,日,時間段,那麼你需要的時候,你在區間呼籲toPeriod指定的週期類型:

Period period = interval.toPeriod(PeriodType.yearMonthDayTime()); 

結果:

i/p=> now =Tue Oct 18 12:15:50 IST 2016 
     time=Mon Sep 26 14:38:36 IST 2016 

o/p=> s=14 
     m=37 
     h=21 
     days=21 
     mo=0 
     y=0 

當然,這個例子中的月份和年份字段仍然爲0,因爲這兩個日期間隔不到一個月。