从java日期减去毫秒数会产生意外结果[重复]

时间:2022-08-25 18:13:12

This question already has an answer here:

这个问题在这里已有答案:

I need to subtract several months of time from a java.util.Date object to get a different java.util.Date. I know that there is a simple way to do this in java 8, however this must be run on my school's server that does not support java 8. My current solution looks like this:

我需要从java.util.Date对象中减去几个月的时间来获取不同的java.util.Date。我知道有一种简单的方法可以在java 8中执行此操作,但是这必须在我学校的服务器上运行,该服务器不支持java 8.我当前的解决方案如下所示:

int numDaysToSubtract = 60;
Date curDate = new Date();

//subtract numdays * hours/day * mins/hour * secs/min * millisecs/sec
Date newDate = new Date(curDate.getTime() - (numDaysToSubtract * 24 * 3600 * 1000));

curDate is 4/12/2018 and the calculated newDate is 4/2/2018, which is clearly not 60 days before 4/12/2018.

curDate是4/12/2018,计算的新日期是4/2/2018,显然不是在2012年4月12日之前的60天。

Why isn't this working as expected?

为什么这不按预期工作?

What should I try instead?

我该怎么办呢?

1 个解决方案

#1


3  

You have overflowed the number of milliseconds to subtract, because the product doesn't fit in a 32-bit integer, whose maximum value is about 2.1 billion (10 digits).

您已经溢出了要减去的毫秒数,因为该产品不适合32位整数,其最大值约为21亿(10位)。

60 days worth of milliseconds is 5,184,000,000, over the limit. Because of the overflow, the product is calculated at 889,032,704 milliseconds, or about 10.2 days.

60天的毫秒数是5,184,000,000,超过限制。由于溢出,产品计算为889,032,704毫秒,或大约10.2天。

Either cast numDaysToSubtract as a long, or declare it to be long to begin with, to force long calculations, avoiding overflow. For me, doing that results in February 11, 2018, 60 days ago.

要么将numDaysToSubtract转换为long,要么将其声明为很长,以强制进行长时间计算,避免溢出。对我来说,这样做的结果是在2018年2月11日,60天前。

#1


3  

You have overflowed the number of milliseconds to subtract, because the product doesn't fit in a 32-bit integer, whose maximum value is about 2.1 billion (10 digits).

您已经溢出了要减去的毫秒数,因为该产品不适合32位整数,其最大值约为21亿(10位)。

60 days worth of milliseconds is 5,184,000,000, over the limit. Because of the overflow, the product is calculated at 889,032,704 milliseconds, or about 10.2 days.

60天的毫秒数是5,184,000,000,超过限制。由于溢出,产品计算为889,032,704毫秒,或大约10.2天。

Either cast numDaysToSubtract as a long, or declare it to be long to begin with, to force long calculations, avoiding overflow. For me, doing that results in February 11, 2018, 60 days ago.

要么将numDaysToSubtract转换为long,要么将其声明为很长,以强制进行长时间计算,避免溢出。对我来说,这样做的结果是在2018年2月11日,60天前。