当前位置: 首页 > 面试题库 >

在java中得到日期之间的天数差异

黄逸清
2023-03-14
问题内容

我正在尝试这样的事情,我试图从组合框中获取日期

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

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


问题答案:
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所指出的,在超过夏令时(或leap秒)时,这将不起作用,并且在一天中的不同时间使用时,也可能无法给出预期的结果。使用JodaTime可能更容易获得正确的结果,因为我知道8之前纯Java的唯一正确方法是使用Calendar的add和before/ after方法检查和调整计算:

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


 类似资料:
  • 问题内容: 我需要找到两个日期之间的天数:一个是来自报表,另一个是当前日期。我的片段: 这是一个私有方法,并且today是Date对象,仅供您说明。我关注了Java论坛中的两篇文章Thread 1 / Thread 2。 它在独立程序中可以正常工作,尽管当我将其包含在逻辑中以从报告中读取时,我会在值上获得不同寻常的区别。 为什么会发生,如何解决? 编辑: 与实际天数相比,我得到的天数更多。 问题答

  • 问题内容: 我想得到两个Java Date对象之间的区别。我使用了Joda-Time库。但是问题是我得到的天数差异大于实际的天数差异。 这是我的代码段: 这是我的输出: 在这里,为什么将“ 06/22/2010”设为1月22日?有人遇到类似的问题吗? 帮我朋友..提前感谢.. 问题答案: 月份是MM 在您的情况下: DateFormat formatter = new SimpleDateForm

  • 问题内容: 在我的代码中,日期之间的差异是错误的,因为它应该是38天而不是8天。我该如何解决? 问题答案: 问题出在变量中。月以Capital M表示。 尝试更改为: 有关更多信息,请参见此javadoc。 编辑: 这是代码,如果您想以注释的方式打印差异: 希望对您有所帮助!

  • 事件日期为:(来自日期选择器对话框) 我在计算他们之间的天差...我找到的最短的东西是: 而第一个对象是“今天”,第二个对象是“eventToDisplay.getEventDate()它对我不起作用,它显示了错误的天数。 我也尝试过这样做: 也没用。。。我也试着在没有乔达时间的情况下做这件事,因为我遇到了麻烦,因为我试图用日期和时间来做。。。 我发现的其他事情是漫长而复杂的,我想也许有更好的方法

  • 问题内容: Java类库具有一个名为DateTime的类。DateTime具有此方法: 该参数返回此参数与参数之间的天数。它没有方法 我碰巧需要的。是否有一个类似于DateTime但有这种方法的类? 问题答案: 不熟悉DateTime … 如果您有两个日期,则可以对它们调用getTime以获取毫秒,获取diff并除以1000。例如 如果您有日历对象,则可以调用 并做同样的

  • 如何计算两个日期之间的秒差? 我有这个: 在这种情况下,时间是: