得到java中日期之间的差异 [英] getting the difference between date in days in java

查看:101
本文介绍了得到java中日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何使用java计算两个日期之间的差异

我正在尝试这样的东西,
我想从组合框中获取日期

I'm trying something like this, where I'm trying to get the date from comboboxes

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());

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

I'm not able to subtract the end and start date How do I get the difference between the start date and end date??

推荐答案

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.");

当橙色指出的夏令时间(或闰秒)在使用不同时间的时候不会给出预期的结果。使用JodaTime可能会更容易获得正确的结果,因为我知道纯Java的唯一正确方法是使用日历的添加和之前/之后的方法来检查和调整计算:

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java I know is to use Calendar's add and before/after methods to check and adjust the calculation:

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--;
}

这篇关于得到java中日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆