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
我也試過LocalDate
和DateTime
但有同樣的問題。
'simpleDateFormat.parse(simpleDateFormat.format(x))'是什麼點? – Andreas
你的約會距離不到一個月,所以你幾個月得到'0'這個事實並不令人驚訝。但是,天應該不爲零。如果您使用Java 8,則會有一個新的內置日期/時間庫(由執行JodaTime的人員創建),其中包括一個新的格式化程序/解析器。 –
因爲是3周,所以你得到了0天。 'period.getWeeks()'返回3.您可以很容易地找到與我一樣的方式,只需打印期間:'P3WT21H37M14S' – Andreas