Date nowdate = new Date();
long nowms = nowdate.getTime();
long differencems = numdaysback * 24 * 60 * 60 * 1000;
long thenms = nowms - differencems;
Date thendate = new Date(thenms);
如果 numdaysback 是 365,那么我认为 thendate 应该是一年前。但这不是……大约三周前?!?
NUMDAYSBACK: 365
NOWDATE: Wed Jun 22 20:31:58 SGT 2011
NOWMS: 1308745918625
DIFFERENCEMS: 1471228928
THENMS: 1307274689697
THENDATE: Sun Jun 05 19:51:29 SGT 2011
最佳答案
怎么样:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
Date thendate = cal.getTime();
无论夏令时或闰年如何,返回一天中的同一时间,更短更清晰...
通常 Calendar
是这种情况下的方法(除非您使用像 Joda Time 这样的第三方库)。您可以将它用于各种计算:添加 N 天/小时/月/秒,将时间截断为整整一个小时等 - 仅使用 long
会非常痛苦的东西。
关于你原来的问题,它似乎是整数溢出的受害者。如果乘法显式使用 long,它会起作用:
long differencems = 365 * 24 * 60 * 60 * 1000L;
关于Java Date 问题,找到 X 天前的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6439946/