2014-11-17 15 views
0

我有當前的日期,我想只用java.util.Date如何獲得java.util.Date這是今年比當前日期回不使用的SimpleDateFormat或日曆

得到這也是日起1年內回

我在GWT工作,所以SimpleDateFormatCalendar

Date currentDate = new Date(); 
Date oneYearBefore = new Date(- (365 * 24 * 60 * 60 * 1000)); 

上面提到的代碼是不能工作

+0

該表達式將溢出int數據類型。嘗試使用長常量。 (例如365L * 24L * 60L ...)。此外,您還沒有考慮夏令時或閏秒。他們對你的用例很重要嗎? – kiwiron

+0

這會給你帶來很多痛苦,因爲你還必須檢查閏年等。 – SpaceTrucker

+0

[如何在Java GWT中執行日曆操作?如何將日期添加到日期?](http://stackoverflow.com/questions/2527845/how-to-do-calendar-operations-in-java-gwt-how-to-add-days-toa-a-日期) – SpaceTrucker

回答

0

你正在使用所有的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 
+0

這裏有個bug,它應該是:long milliseconds =(long)365 * 24 * 60 * 60 * 1000; Date oneYearBefore = new Date(currentDate.getTime() - milliseconds); – lazywiz

3

使用日曆類

(從一些論壇得到了它)不能使用
Calendar calendar = Calendar.getInstance(); 
calendar.add(Calendar.YEAR, -1); 
System.out.println(calendar.getTime()); 
0

爲什麼你不能使用日曆?我想你可能誤解了一些東西?

反正:

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)); 
+1

一年並不總是24小時365次。 – Jesper

+0

http://img3.wikia.nocookie.net/__cb20090707173543/wykopedia/pl/images/9/9b/200px-CaptainobviousChooseOption.jpg 你喜歡給我們一個很好的公曆日曆嗎?在大多數應用中這是足夠的。 – maslan

+0

我想在gwt我不允許使用日曆。它說在運行時沒有找到java.util.Calendar的源代碼。 – Rakesh

0

只使用java.util.Date,您可以使用:

Date oneYearBefore = new Date(currentDate.getTime() - (365L * 24L * 60L * 60L * 1000L)); 

但請記住,這沒有考慮到潛在的閏年。

相關問題