System.currentTimeMillis()的减法运算

4
    long rt = System.currentTimeMillis()-(1000*60*60*24*30);

当我将上述变量rt转换为日期时,我无法得到预期的日期(即)30天前。为什么?


请使用日期/时间API进行此类计算: http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html - Maciej
1
展示你用来转换的代码 - someone
这是一个整型溢出。将其更改为1000L - shmosel
1个回答

7

1000*60*60*24*30的结果导致int溢出,因为它比Integer.MAX_VALUE大。将其更改为1000L*60*60*24*30以使用long

例如:

long rt = System.currentTimeMillis()-(1000L*60*60*24*30);
System.out.println (new Date(rt));

为我打印:

Sun Feb 25 09:18:58 IST 2018

该死,你比我快了... 我曾经用过一个与此类似的例子作为Java谜题。 - Michael Berry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接