在java中获取日期(以天为单位)之间的差异

2022-09-01 04:13:44

可能的重复:
如何使用java计算两个日期之间的差异

我正在尝试类似的东西,我试图从组合框中获取日期

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();  

int Sdate=Integer.parseInt(cmbSdate.getSelectedItem().toString());  
int Smonth=cmbSmonth.getSelectedIndex();
int Syear=Integer.parseInt(cmbSyear.getSelectedItem().toString());  

int Edate=Integer.parseInt(cmbEdate.getSelectedItem().toString());
int Emonth=cmbEmonth.getSelectedIndex();
int Eyear=Integer.parseInt(cmbEyear.getSelectedItem().toString());

start.set(Syear,Smonth,Sdate);  
end.set(Eyear,Emonth,Edate);

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String startdate=dateFormat.format(start.getTime());  
String enddate=dateFormat.format(end.getTime());

我无法减去结束日期和开始日期 如何获得开始日期和结束日期之间的差异?


答案 1
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

正如orange80所指出的那样,这在跨越夏令时(或闰秒)时不起作用,并且在使用一天中的不同时间时可能不会给出预期的结果。使用JodaTime可能更容易获得正确的结果,因为在8之前使用纯Java的唯一正确方法是使用Calendar的添加和之前/之后方法来检查和调整计算:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

答案 2

为此,请使用JodaTime。它比标准的Java DateTime Apis好得多。以下是JodaTime中用于计算天差的代码:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }