我有当前的日期,我想只用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