如何在Java中检查2个日期是否在同一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22439314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:43:32  来源:igfitidea点击:

How to check if 2 dates are on the same day in Java

javadate

提问by Yahya Uddin

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

我有 2 个日期变量,Date1 和 Date2。我想检查日期 1 是否与日期 2 位于同一日期(但允许它们具有不同的时间)。

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????

编辑:我的组织想法是删除小时、分钟、秒,但这些功能在 Java 中被标记为折旧。那我应该用什么???

采纳答案by Meno Hochschild

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

虽然基于的日期组成部分给出的答案java.util.Date是足以在很多地方,我想强调的一点,一个java.util.Date不是一个日期,但以毫秒计一种UNIX的时间戳。这样做的后果是什么?

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

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

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.

但考虑例如西萨摩亚在 2011 年穿越国际java.util.Date日期变更线的情况。您可以拥有类型为 的有效时间戳,但如果您考虑萨摩亚的日期部分,您甚至可以获得无效日期(2011-12-30 在萨摩亚从未存在过本地),因此仅比较日期部分可能会失败。此外,根据时区,日期组件通常可以与 UTC 区域中的本地日期相差一天,提前或推迟,在最坏的情况下甚至有两天的差异。

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.

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

回答by silfrede

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

回答by Aneliram

When you use the toString() method what do you get? Is it only the year/month/day or time too? If it is then you could simply compare the strings of the two objects. (date1.toString().equals(date2.toString()));

当您使用 toString() 方法时,您会得到什么?是否也只是年/月/日或时间?如果是,那么您可以简单地比较两个对象的字符串。(date1.toString().equals(date2.toString()));

回答by Sourabh Bhat

Why don't you simply compare the year, month and day? You can write your method for doing it something like:

为什么不简单地比较年月日?你可以编写你的方法来做这样的事情:

private boolean isDateSame(Calendar c1, Calendar c2) {
    return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && 
            c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
            c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
}

回答by Basil Bourque

Today = Span Of Time

今天 = 时间跨度

While the other answers may be correct, I prefer the approach where we recognize that "today" is actually a span of time.

虽然其他答案可能是正确的,但我更喜欢我们认识到“今天”实际上是一个时间跨度的方法。

Because of anomalies such as Daylight Saving Time (DST), days vary in length, not always 24 hours long. Here in the United States, some days are 23 hours long, some 25.

由于夏令时 (DST) 等异常情况,日子的长度各不相同,并非总是 24 小时。在美国,有些日子是 23 小时,有些是 25 小时。

Half-Open

半开

Commonly in data-time work, we use the "Half-Open" strategy where the beginning of a span is inclusive and the ending is exclusive. So that means "today" spans from the first moment of today up to, but not including, the first moment of tomorrow.

通常在数据时间工作中,我们使用“半开”策略,其中跨度的开始是包含的,而结束是不包含的。所以这意味着“今天”从今天的第一个时刻到但不包括明天的第一个时刻。

Time Zones

时区

Time zones are critical, as explained in the correct answer by Meno Hochschild. The first moment of a day depends on its time zone rules.

正如Meno Hochschild正确答案中所解释的那样,时区至关重要。一天的第一个时刻取决于其时区规则。

Joda-Time

乔达时间

The Joda-Timelibrary has nice classes for handling spans of time: Period, Duration, and Interval.

乔达时库具有良好的班的时间跨度处理:周期,持续时间和间隔

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays(1).withTimeAtStartOfDay() );

DateTime dateTimeInQuestion = new DateTime( date ); // Convert java.util.Date.
boolean happensToday = today.contains( dateTimeInQuestion );

Benefits

好处

This approach using a span of time has multiple benefits:

这种使用时间跨度的方法有多种好处:

  • Avoids Daylight Saving Time (DST) issues
  • Lets you compare date-time values from other time zones
  • Flexible, so you can use the same kind of code for other spans (multiple days, months, etc.)
  • Gets your mind shifted away from calendar dates (a layered abstraction) and onto date-times as points on a flowing timeline (the underlying truth).
  • 避免夏令时 (DST) 问题
  • 允许您比较来自其他时区的日期时间值
  • 灵活,因此您可以对其他跨度(多天、几个月等)使用相同类型的代码
  • 让您的注意力从日历日期(分层抽象)转移到日期时间作为流动时间轴上的点(基本事实)。


Java 8has a new java.time packagebuilt-in. These new classes are modeled after Joda-Time but are entirely re-architected. This same kind of code can be written using java.time.

Java 8内置了一个新的java.time 包。这些新类以 Joda-Time 为模型,但完全重新构建。可以使用 java.time 编写相同类型的代码。