英文:
System.currentTimeMillis() is acting weird
问题
这是我的代码块来展示奇怪之处。
我正在比较两个时间,以毫秒为单位。时间t1是在74天后的毫秒数,而时间t2是在90天后的毫秒数。我的期望是t1 < t2,但实际上它显示t1大于t2。它在控制台上打印出FAILED。相同的代码在JavaScript中正常运行,与预期相符。
class CompareDates {
public static void main(String[] args) {
long t1 = System.currentTimeMillis() + (74 * 24 * 60 * 60 * 1000);
long t2 = System.currentTimeMillis() + (90 * 24 * 60 * 60 * 1000);
if (t1 <= t2) {
System.out.println("PASSED");
} else {
System.out.println("FAILED");
}
}
}
英文:
Here is my code block to show the weirdness.
I'm comparing two times in milli seconds. Time t1 is in milliseconds after 74 days and time t2 is in milliseconds after 90 days. My expectation is t1 < t2, but actually it shows t1 is greater than t2. It prints FAILED on the console. Same code runs fine in Javascript as expected.
class CompareDates {
public static void main(String[] args) {
long t1 = System.currentTimeMillis()+(74*24*60*60*1000);
long t2 = System.currentTimeMillis()+(90*24*60*60*1000);
if(t1 <= t2 ) {
System.out.println("PASSED");
} else {
System.out.println("FAILED");
}
}
}
答案1
得分: 8
74*24*60*60*1000
溢出 int
。为了防止溢出,将第一个操作数添加 L
,以便将每个乘法都以 long
进行计算:74L*24*60*60*1000
。
英文:
74*24*60*60*1000
overflows int
. To prevent it, add L
to the first operand in order to do every multiplication in long
: 74L*24*60*60*1000
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论