纪元时间是自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));
Run Code Online (Sandbox Code Playgroud)
它给出了以下输出
Mon Dec 26 06:07:19 GMT 2016
Tue Dec 06 13:04:32 GMT 2016
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用Calendar类来解决这个问题,但只是想了解这种行为
小智 5
因为JVM将乘法值30*24*60*1000视为Int并且乘法结果超出Integer的范围它会给出结果:-1702967296意图为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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3916 次 |
| 最近记录: |