计算Java日期的差异 [英] Calculating difference in dates in Java
问题描述
我知道简单的方法是以毫秒为单位,将时间的差异转换成几天。但是,我想知道这是否适用于所有情况(夏令时等)。
我知道简单的方法是以
的时间差为单位,以
为单位,然后将其转换为天数。
但是,我想知道这个
是否适用于所有情况(日光
保存等)。
如果您的时间来自UTC日期,或者它们只是在同一系统上测量的两次对System.getCurrentTimeMillis()的调用之间的差异,您将获得有效的毫秒数作为差异,而与任何时区问题。 (这就是为什么一切都应该使用UTC作为存储格式 - 从UTC->本地时间来说更容易;如果你尝试去另一种方式,那么你需要将本地时区与本地时间一起存储 - 或尝试推断它,gack!)
至于把它变成几天,你应该能够划分86400000 ...有一个警告,
每隔一年左右会有一次闰秒。
I find it funny that Java (or the java.util library) does not have a built-in function to calculate difference in dates. I want to subtract one date from another to get the elapsed time between them. What is the best way to do this?
I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, I wanted to know if this works in all cases (with daylight saving, etc.).
I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, i wanted to know if this works in all cases (with daylight saving, etc.).
If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTimeMillis() measured on the same system, you will get a valid number of milliseconds as the difference, independent of any timezone issues. (which is why everything should be using UTC as a storage format -- it's much easier to go from UTC->local time; if you try to go the other way then you need to store the local timezone along with the local time -- or attempt to infer it, gack!)
As for turning this into a number of days, you should just be able to divide by 86400000... with the caveat that there is an occasional leap second every other year or so.
这篇关于计算Java日期的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!