2014-11-17 17 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)); 

但请记住,这没有考虑到潜在的闰年。

相关问题