这不是我的工作,在这里找到了答案。不希望将来:)断开链接。
关键是这条线用于考虑日光设置,参考完整代码。
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
或者尝试作为参数传递给 和 和 对象并调用 。TimeZone
daysBetween()
setTimeZone()
sDate
eDate
所以它在这里:
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millisecond in second
return cal; // return the date part
}
getDatePart() 取自这里
/**
* This method also assumes endDate >= startDate
**/
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"));
//diff between these 2 dates should be 1
Date d1 = new Date("01/01/2007 12:00:00");
Date d2 = new Date("01/02/2007 12:00:00");
//diff between these 2 dates should be 1
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);
}
/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public static long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Date startDate, Date endDate) {
...
}
输出:
手动 - 介于:2007 年 1 月 1 日和 2007 年 1 月 2 日之间的天数为: 1
日历 - 介于: 01-Jan-2007 和 02-Jan-2007 之间的天数是: 1
手动 - 介于: 24-Mar-2007 和 25-Mar-2007 之间的天数是: 0
日历 - 介于: 24-Mar-2007 和 25-Mar-2007 之间的天数是: 1