【发布时间】:2020-06-05 16:18:12
【问题描述】:
我遇到了一个麻烦的问题,我无法真正向自己解释它为什么会出现。
基本上我想为时间戳添加时间(一个简单的长整数)。
我理解如下。如果我将时间添加到时间戳,我将在未来结束。如果我将时间减去时间戳,我将在过去结束。
在我的示例中,情况正好相反。如果我在时间戳中添加一些内容,则它会减少,如果我减去一些内容,则会添加。
public class MyClass {
public static void main(String args[]) {
static final int MONTH_IN_SECONDS = 2629743;
final long current = System.currentTimeMillis();
System.out.println("Current: " + current);
final long future = System.currentTimeMillis() + (MONTH_IN_SECONDS * 1000 * 3);
System.out.println("Addition: " + future);
final long past = System.currentTimeMillis() - (MONTH_IN_SECONDS * 1000 * 3);
System.out.println("Subtraction: " + past);
}
}
结果(比较前 5 个字符):
Current: 1582275101365
Addition: 1581574395774 // smaller than current even though it should be greater
Subtraction: 1582975806958 // great than current even though it should be smaller
为什么会这样?术语(MONTH_IN_SECONDS * 1000 * 3) 是否溢出,因为它只是一个整数,因此计算不起作用(或以负值结尾)?
如果我将术语更改为(MONTH_IN_SECONDS * 1000L * 3),它似乎可以正常工作。是不是因为完整的术语被转换为long?
【问题讨论】:
-
目前还不清楚打印过程中“减法”如何变为“减”,但无论如何。你已经自己回答了你的问题。您可以通过
System.out.println(MONTH_IN_SECONDS*1000*3);... 简化它... -
您似乎已经回答了您的问题。你所有的猜测都是正确的。这是由于溢出,如果您使用
1000L,则完整的术语确实会变为long。 -
我使用 Netbeans 作为 IDE,它没有将此标记为可能的问题。 IntelliJ 显示一条消息,表明它可能会导致问题,因此如果我使用不同的 IDE,则可以防止该问题
标签: java math timestamp integer long-integer