java - 在java 7中将2个日期之间的差异转换为天数

标签 java datetime calendar simpledateformat timeunit

我想在java中比较2个日期,需要将2个日期之间的差异转换为天

//Setting up date
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 16);
Date d = cal.getTime();

输出如下:Sun Jun 16 11:04:57 UTC 2019

//Getting the current date instance
Calendar cal1 = Calendar.getInstance();
Date d1 = cal1.getTime();

输出如下:Mon Jul 08 11:04:57 UTC 2019

需要获取 d 和 d1 之间的天数差异。

预先感谢您花时间提供解决方案

最佳答案

在这里,您只需做简单的数学计算。

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

这在跨越夏令时(或闰秒)时不起作用,并且在使用一天中的不同时间时也可能无法给出预期结果。您可以这样修改:

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 - 在java 7中将2个日期之间的差异转换为天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56938992/

相关文章:

java - 从现有列表创建元素列表

php - 在 2 周内获取 php 日期

java - jsp web 应用程序相对路径

java - 使用 JPA 映射复合主键和外键

Java - 如何检查数据库中的现有用户(用于注册界面)?

java - 无法从 TemporalAccessor : {}, ISO 获取 ZoneOffset,Europe/Berlin 解析为 java.time.format.Parsed 类型的 2019-12-26

python - 类型错误 : '>=' not supported between instances of 'datetime.date' and 'str'

javascript - 如何在每个时间段检测到最大条目时更改日历覆盖

php - 使用 PHP-EWS 访问另一个邮箱日历事件

c# - 一个窗口中有 25 个 WPF 日历,打开窗口需要 5 秒