比较两个 java.util.Dates 看它们是否在同一天 [英] Comparing two java.util.Dates to see if they are in the same day

查看:28
本文介绍了比较两个 java.util.Dates 看它们是否在同一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较两个 Date(例如 date1date2)并得出一个 boolean sameDay 两个 Date 共享同一天为真,否则为假.

I need to compare two Dates (e.g. date1 and date2) and come up with a boolean sameDay which is true of the two Dates share the same day, and false if they are not.

我该怎么做?这里似乎有一股混乱的旋风……如果可能的话,我想避免引入 JDK 之外的其他依赖项.

How can I do this? There seems to be a whirlwind of confusion here... and I would like to avoid pulling in other dependencies beyond the JDK if at all possible.

澄清:如果 date1date2 共享相同的年月日,则 sameDay为真,否则为假.我意识到这需要时区知识……传入时区会很好,但只要我知道行为是什么,我就可以接受格林威治标准时间或当地时间.

to clarify: if date1 and date2 share the same year, month, and day, then sameDay is true, otherwise it is false. I realize this requires knowledge of a timezone... it would be nice to pass in a timezone but I can live with either GMT or local time as long as I know what the behavior is.

再次澄清:

date1 = 2008 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
  => sameDate = true

date1 = 2009 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
  => sameDate = false

date1 = 2008 Aug 03 12:00:00
date2 = 2008 Jun 03 12:00:00
  => sameDate = false

推荐答案

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
                  cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);

请注意,当涉及不同的时区时,同一天"并不像听起来那么简单.上面的代码将为两个日期计算相对于它运行的计算机使用的时区的日期.如果这不是您所需要的,您必须在确定同一天"的确切含义后,将相关时区传递给 Calendar.getInstance() 调用.

Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".

是的,Joda Time 的 LocalDate 将使整个过程更加简洁和轻松(尽管会存在涉及时区的相同困难).

And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).

这篇关于比较两个 java.util.Dates 看它们是否在同一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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