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 * 360;
dtNow.setTime(dlong);
tempStr = df.format(dtNow);
System.out.println("之后时刻:" +tempStr);
运行结果:
现在时刻:2013-01-23 09:34:51
之后时刻:2013-01-11 08:54:22
如果是以上代码,那么1000 * 60 * 60 * 24 * 360就为int类型的,其最大取值为:System.out.println(Integer.MAX_VALUE); 结果:2147483647
而System.out.println(1000 * 60 * 60 * 24 * 360); 实际值是:1039228928,因为已超出范围,所以结果是这个了。
而System.out.println(1000 * 60 * 60 * 24 * 360L); 实际值是:31104000000,可以看出已经超出了,其最大值,所以最后结果是错误的。
改成一下代码:
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 * 360L;
dtNow.setTime(dlong);
tempStr = df.format(dtNow);
System.out.println("之后时刻:" +tempStr);