这不是我的作品,我在这里找到了答案。未来不想有损坏的链接 :)
关键是要考虑夏令时设置,参见完整代码。
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
或者尝试将 TimeZone
作为参数传递给 daysBetween()
方法,并在 sDate
和 eDate
对象上调用 setTimeZone()
方法。
那么就这样吧:
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
从这里获取的getDatePart()。
public static long daysBetween(Date startDate, Date endDate) {
Calendar sDate = getDatePart(startDate);
Calendar eDate = getDatePart(endDate);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
细节注意:
计算两个日期之间的差异并不像减去两个日期并将结果除以(24 * 60 * 60 * 1000)那样简单。事实上,这是错误的!
例如: 03/24/2007和03/25/2007之间的差异应该是1天;然而,在英国,使用上述方法,你会得到0天!
请自行查看以下代码。使用毫秒方式进行计算会导致四舍五入误差,特别是在出现夏令时等小问题时变得最明显。
完整代码:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateTest {
public class DateTest {
static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Date d1 = new Date("01/01/2007 12:00:00");
Date d2 = new Date("01/02/2007 12:00:00");
Date d3 = new Date("03/24/2007 12:00:00");
Date d4 = new Date("03/25/2007 12:00:00");
Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);
Calendar cal3 = Calendar.getInstance();cal3.setTime(d3);
Calendar cal4 = Calendar.getInstance();cal4.setTime(d4);
printOutput("Manual ", d1, d2, calculateDays(d1, d2));
printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2));
System.out.println("---");
printOutput("Manual ", d3, d4, calculateDays(d3, d4));
printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4));
}
private static void printOutput(String type, Date d1, Date d2, long result) {
System.out.println(type+ "- Days between: " + sdf.format(d1)
+ " and " + sdf.format(d2) + " is: " + result);
}
public static long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
public static long daysBetween(Date startDate, Date endDate) {
...
}
输出:
手动计算 - 从 2007 年 1 月 1 日到 2007 年 1 月 2 日之间的天数为:1
日历计算 - 从 2007 年 1 月 1 日到 2007 年 1 月 2 日之间的天数为:1
手动计算 - 从 2007 年 3 月 24 日到 2007 年 3 月 25 日之间的天数为:0
日历计算 - 从 2007 年 3 月 24 日到 2007 年 3 月 25 日之间的天数为:1