Java日历:获得两个日期/时间之间的差异-减一 [英] Java Calendar: Getting Difference Between Two Dates/Times - Off by One

查看:209
本文介绍了Java日历:获得两个日期/时间之间的差异-减一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到许多有关此主题的问题和答案,但是都没有解决我的特定问题。我扩展了Java Calendar类(标准-没有第三方库),并且需要找出两个任意日期之间的差异。

I have seen many questions and answers on this topic, but none addressed my particular problem. I extended the java Calendar class (standard--no third party libraries), and needed to find the difference in days between two arbitrary dates.

方法:


  1. 将两个日期的时间都更改为午夜。

  2. 将日期转换为毫秒

  3. 查找两个日期之间的差。

  4. 将结果除以一天中的毫秒数(24 * 60 *
    60 * 1000)。

  5. 结果应该是天数之差。

  1. Change the time of both dates to midnight.
  2. Convert the dates to milliseconds.
  3. Find the difference between the two dates.
  4. Divide the result by the number of milliseconds in a day (24 * 60 * 60 * 1000).
  5. The result should be the difference in days.

有时是,有时不是。甚至同一天的测试也可能相差一倍。

And it sometimes is, and it sometimes isn't. Even tests on the same date can be off by one. What's going on?

推荐答案

如其他用户所建议的,您还需要将日历的毫秒值设置为零才能进行比较只有日期。可以使用以下代码段实现这一点:

As suggested by other users, you need to also set the millisecond value of the calendars to zero to compare only the dates. This can be achieved with the following code snippet:

someCalendar.set(Calendar.MILLISECOND, 0)

此外,请注意,时区变化(例如,从冬天到夏天的时间变化)可能意味着在2006年8月30日之前或之后,一天。

Also, note that timezone changes (e.g. moving from winter time to summer time) may mean there is more or less than 86,400,000 ms in a day.

这篇关于Java日历:获得两个日期/时间之间的差异-减一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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