日期:2014-05-19  浏览次数:20669 次

java 时间离现在若干小时时刻的代码怎么会有时候对有时候错呢?
我的代码如下:
String tempStr = "";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dtNow = new Date();
System.out.println("现在时刻:" + df.format(dtNow));
long dlong = dtNow.getTime() - 1000 * 60 * 60 * 24 * 3;
dtNow.setTime(dlong);
tempStr = df.format(dtNow);
System.out.println("之后时刻:" +tempStr);
以上是计算3天之前的时刻;
执行结果如下:
现在时刻:2013-01-22 18:18:08
之后时刻:2013-01-19 18:18:08是正确的!
如果改成30天之前的时刻;
执行结果如下:
现在时刻:2013-01-22 18:20:07
之后时刻:2013-02-11 11:22:54是错误的,请问为什么呢?如何计算正确?

------解决方案--------------------
楼主这是要做什么?用相关的Utils类吧。。
日期类型用DateUtils,字符串用StringUtils
------解决方案--------------------

System.out.println(Integer.MAX_VALUE);
System.out.println(1000 * 60 * 60 * 24 * 30);

这样也许就明白了吧.
已经超过了int的最大值了.所以时间超过30天就不准确了.

改为
long dlong = dtNow.getTime() - 1000 * 60 * 60 * 24 * 30L;