计算Java中的日期差异 [英] Calculating difference in dates in Java

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

问题描述

我觉得 Java(或 java.util 库)没有内置函数来计算日期差异,这很有趣.我想从另一个日期中减去一个日期以获得它们之间经过的时间.做这个的最好方式是什么?

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

如果您的时间来自 UTC 日期,或者它们只是在同一系统上测量的两次 System.getCurrentTimeMillis() 调用之间的差异,您将获得有效的毫秒数作为差异,与任何时区问题无关.(这就是为什么一切都应该使用 UTC 作为存储格式的原因——从 UTC-> 本地时间开始要容易得多;如果你尝试相反的方式,那么你需要将本地时区与本地时间一起存储——或尝试推断它,gack!)

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!)

至于将其转换为天数,您应该只能除以 86400000...但需要注意的是,偶尔会出现 闰秒 每隔一年左右.

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屋!

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