将天数添加到纪元时间 [Java]

Adding days to Epoch time [Java]

大纪元时间是自 1970 年 1 月 1 日以来经过的毫秒数,因此如果我想在该时间上增加 x 天,添加相当于 x 天的毫秒数似乎很自然得到结果

Date date = new Date();
System.out.println(date);
// Adding 30 days to current time
long longDate = date.getTime() + 30*24*60*60*1000;
System.out.println(new Date(longDate));

它给出以下输出

Mon Dec 26 06:07:19 GMT 2016
Tue Dec 06 13:04:32 GMT 2016

我知道我可以使用 Calendar class 来解决这个问题,但只是想了解这种行为

因为 JVM 将乘法 30*24*60*1000 的值视为 Int 并且乘法结果超出了 Integer 的范围,所以它会给出结果:-1702967296 intends of 2592000000 所以它给出的日期小于当前日期

试试下面的代码:

public class Test {
public static void main(final String[] args) {
    Date date = new Date();
    System.out.println(date);
    // Adding 30 days to current time
    System.out.println(30 * 24 * 60 * 60 * 1000); // it will print -1702967296
    long longDate = (date.getTime() + TimeUnit.DAYS.toMillis(30));
    System.out.println(TimeUnit.DAYS.toMillis(30));
    date = new Date(longDate);
    System.out.println(date);
 }
}

试试这个:

 DateTime timePlusTwoDays = new DateTime().plusDays(days);
 long longDate = timePlusTwoDays.getTime();
 System.out.println(new Date(longDate));

Dateime class 有:

 public DateTime plusDays(int days) {
        if (days == 0) {
            return this;
        }
        long instant = getChronology().days().add(getMillis(), days);
        return withMillis(instant);
 }

您的号码出现整数溢出。 30*24*60*60*1000 = 2,592,000,000,大于有符号的 32 位整数可以容纳 (2,147,483,647)。

改为使用多头,通过将 L 附加到任何数字上:例如 1000L

请注意,如果您想处理夏令时(更不用说闰秒了!),这仍然不够。但是,如果您愿意假设一天始终恰好是 24 小时,那么使用 longs 将解决您的问题。 (时间是一件复杂的事情,我建议使用像 joda 或 Java 8 的 类 这样的库来为你处理它!)

按如下方式编辑您的代码:

long longDate = date.getTime() + 30*24*60*60*1000L;

一定会成功的。