了由于整数溢出导致的日期计算错误,以及使用长整型的解决方法。但更好的方式是使用专业的日期类进行日期计算。
private static void wrong1() {
System.out.println("wrong1");
Date today = new Date();
Date nextMonth = new Date(today.getTime() + 30 * 1000 * 60 * 60 * 24);
System.out.println(today);
System.out.println(nextMonth);
}
private static void wrong1fix() {
System.out.println(30 * 1000 * 60 * 60 * 24 + " " + (30L * 1000 * 60 * 60 * 24 > Integer.MAX_VALUE));
System.out.println("wrong1fix");
Date today = new Date();
Date nextMonth = new Date(today.getTime() + 30L * 1000 * 60 * 60 * 24);
System.out.println(today);
System.out.println(nextMonth);
}
学习:Java 业务开发常见错误 100 例学习笔记