如何检查Java中的日期是否在同一天 [英] How to check if 2 dates are on the same day in Java

查看:660
本文介绍了如何检查Java中的日期是否在同一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个Date变量Date1和Date2。
我想检查日期1是否与Date2的日期相同(但允许有不同的时间)。



我该怎么做?



看起来真的很简单,但我很挣扎。



编辑:我想以避免外部库和东西



编辑:
我的主意是删除小时,分钟,秒,但这些功能被标记为在Java中折旧。那么我应该怎么用????

解决方案

虽然根据的日期组成部分给出答案, java.util.Date 在许多部分都足够了,我强调,一个 java.util.Date NOT 一个日期,但是以毫秒为单位测量的一种UNIX时间戳。它的后果是什么?



仅限于 Date的比较日期 -timestamps将取决于上下文。例如在UTC时区,仅日期比较是直接的,最终只会比较年,月和日组件,请参阅其他答案(我不需要重复)。



但请考虑例如在2011年跨越国际数据线的西萨摩亚的情况。您可以具有类型为 java.util.Date 的有效时间戳,但如果您考虑他们在萨摩亚的日期部分,你甚至可以得到一个无效的日期(2011-12-30从未存在于萨摩亚本地),所以只是日期部分的比较可能会失败。此外,根据时区,日期组件通常可能与UTC区域的本地日期不同一天,前面或后面,在最坏的情况下,甚至有两天的差异。



所以以下解决方案的扩展稍微更精确:

  SimpleDateFormat fmt = new SimpleDateFormat(yyyyMMdd); 
fmt.setTimeZone(...); //你的时区
return fmt.format(date1).equals(fmt.format(date2));

类似的扩展也存在于更多的编程方法中,首先将juDate-timestamp转换为 java.util.GregorianCalendar ,然后设置时区,然后比较日期组件。


I have 2 Date variables, Date1 and Date2. I want to check if Date 1 fall on the same date as Date2 (but they are allowed to have different times).

How do i do this?

It looks like a really easy thing to do, but i'm struggling.

EDIT: I want to avoid external libraries and stuff

EDIT: My orgional idea was to remove the hour, min, sec but those features are marked as depreciated in Java. So what should I use????

解决方案

Although given answers based on date component parts of a java.util.Date are sufficient in many parts, I would stress the point that a java.util.Date is NOT a date but a kind of UNIX-timestamp measured in milliseconds. What is the consequence of that?

Date-only comparisons of Date-timestamps will depend on the time zone of the context. For example in UTC time zone the date-only comparison is straight-forward and will finally just compare year, month and day component, see other answers (I don't need to repeat).

But consider for example the case of Western Samoa crossing the international dateline in 2011. You can have valid timestamps of type java.util.Date, but if you consider their date parts in Samoa you can even get an invalid date (2011-12-30 never existed in Samoa locally) so a comparison of just the date part can fail. Furthermore, depending on the time zone the date component can generally differ from local date in UTC zone by one day, ahead or behind, in worst case there are even two days difference.

So following extension of solution is slightly more precise:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
fmt.setTimeZone(...); // your time zone
return fmt.format(date1).equals(fmt.format(date2));

Similar extension also exists for the more programmatic approach to first convert the j.u.Date-timestamp into a java.util.GregorianCalendar, then setting the time zone and then compare the date components.

这篇关于如何检查Java中的日期是否在同一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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