Java 日期是同一天,如何检查Java中的日期是否在同一天

在Java中,当需要检查两个日期(Date1和Date2)是否在同一天但允许时间不同,可以不依赖外部库,通过转换日期为只有年月日的形式进行比较。由于java.util.Date实际上是基于UNIX时间戳的,直接比较可能会受到时区影响。解决方法是将日期格式化为'yyyyMMdd',并设置特定时区,然后比较格式化后的字符串是否相等。例如,使用SimpleDateFormat进行格式化并比较。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值