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

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

问题描述

我需要比较两个日期 s(例如 date1 date2 ),并提出一个 boolean sameDay ,这两个 Date 在同一天分享,如果不是,则为false。

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.

来澄清如果 date1 date2 共享同一年,月和日,则 sameDay 为true,否则为false。我意识到这需要一个时区的知识,只要我知道这个行为是什么,那么传递时区是很好的,但是我可以和格林尼治标准时间或本地时间一起生活。

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.YEAR) == cal2.get(Calendar.YEAR) &&
                  cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_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天全站免登陆