我有當前的日期,我想只用java.util.Date
如何獲得java.util.Date這是今年比當前日期回不使用的SimpleDateFormat或日曆
我在GWT工作,所以SimpleDateFormat
或Calendar
Date currentDate = new Date();
Date oneYearBefore = new Date(- (365 * 24 * 60 * 60 * 1000));
上面提到的代碼是不能工作
我有當前的日期,我想只用java.util.Date
如何獲得java.util.Date這是今年比當前日期回不使用的SimpleDateFormat或日曆
我在GWT工作,所以SimpleDateFormat
或Calendar
Date currentDate = new Date();
Date oneYearBefore = new Date(- (365 * 24 * 60 * 60 * 1000));
上面提到的代碼是不能工作
你正在使用所有的int's
,當你乘他們你得到一個int。您將該int轉換爲long,但僅在int乘法已導致錯誤答案後。 其實它是overflowing the int type
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println(currentDate);
long milliseconds = (long) 365 * 24 * 60 * 60 * 1000;
Date oneYearBefore = new Date(currentDate.getTime() - milliseconds);
System.out.println(oneYearBefore);
}
Mon Nov 17 13:11:10 IST 2014
Sun Nov 17 13:11:10 IST 2013
這裏有個bug,它應該是:long milliseconds =(long)365 * 24 * 60 * 60 * 1000; Date oneYearBefore = new Date(currentDate.getTime() - milliseconds); – lazywiz
使用日曆類
(從一些論壇得到了它)不能使用Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
System.out.println(calendar.getTime());
爲什麼你不能使用日曆?我想你可能誤解了一些東西?
反正:
Date oneYearBefore = new Date(System.currentTimeMillis() - (365 * 24 * 60 * 60 * 1000));
或使用您的代碼從論壇貼:
Date currentDate = new Date();
Date oneYearBefore = new Date(currentDate.getTime() - (365 * 24 * 60 * 60 * 1000));
只使用java.util.Date
,您可以使用:
Date oneYearBefore = new Date(currentDate.getTime() - (365L * 24L * 60L * 60L * 1000L));
但請記住,這沒有考慮到潛在的閏年。
該表達式將溢出int數據類型。嘗試使用長常量。 (例如365L * 24L * 60L ...)。此外,您還沒有考慮夏令時或閏秒。他們對你的用例很重要嗎? – kiwiron
這會給你帶來很多痛苦,因爲你還必須檢查閏年等。 – SpaceTrucker
[如何在Java GWT中執行日曆操作?如何將日期添加到日期?](http://stackoverflow.com/questions/2527845/how-to-do-calendar-operations-in-java-gwt-how-to-add-days-toa-a-日期) – SpaceTrucker