Java 如何在没有时间部分的情况下比较两个日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1439779/
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
How to compare two Dates without the time portion?
提问by Arne Evertsson
I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What's the simplest way?
我想要一个 compareTo 方法来忽略 java.util.Date 的时间部分。我想有很多方法可以解决这个问题。最简单的方法是什么?
采纳答案by Jon Skeet
Update: while Joda Time was a fine recommendation at the time, use the java.time
library from Java 8+ instead where possible.
更新:虽然当时 Joda Time 是一个很好的建议,但请java.time
尽可能使用Java 8+ 中的库。
My preference is to use Joda Timewhich makes this incredibly easy:
我更喜欢使用Joda Time这使得这非常容易:
DateTime first = ...;
DateTime second = ...;
LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();
return firstDate.compareTo(secondDate);
EDIT: As noted in comments, if you use DateTimeComparator.getDateOnlyInstance()
it's even simpler :)
编辑:如评论中所述,如果您使用DateTimeComparator.getDateOnlyInstance()
它甚至更简单:)
// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);
("Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date
or java.util.Calendar
. It's a thoroughly superior API. If you're doing anythingsignificant with dates/times, you should really use it if you possibly can.)
(“使用 Joda 时间”是几乎所有关于java.util.Date
or 的SO 问题的基础java.util.Calendar
。这是一个非常出色的 API。如果您正在对日期/时间做任何重要的事情,如果可能的话,您应该真正使用它。)
If you're absolutely forcedto use the built in API, you should create an instance of Calendar
with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)
如果您绝对被迫使用内置 API,您应该创建一个Calendar
具有适当日期和使用适当时区的实例。然后,您可以将每个日历中的时、分、秒和毫秒中的每个字段设置为 0,并比较结果时间。与 Joda 解决方案相比,绝对令人讨厌:)
The time zone part is important: java.util.Date
is alwaysbased on UTC. In most cases where I've been interested in a date, that's been a date in a specific time zone. That on its own will force you to use Calendar
or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)
时区部分是很重要的:java.util.Date
是始终基于UTC。在我对日期感兴趣的大多数情况下,这是特定时区中的日期。这本身将迫使您使用Calendar
或 Joda Time(除非您想自己考虑时区,我不建议这样做。)
Quick reference for android developers
安卓开发者快速参考
//Add joda library dependency to your build.gradle file
dependencies {
...
implementation 'joda-time:joda-time:2.9.9'
}
Sample code (example)
示例代码(示例)
DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();
Date myDateOne = ...;
Date myDateTwo = ...;
int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);
if(retVal == 0)
//both dates are equal
else if(retVal < 0)
//myDateOne is before myDateTwo
else if(retVal > 0)
//myDateOne is after myDateTwo
回答by Adamski
My preference would be to use the Jodalibrary insetad of java.util.Date
directly, as Joda makes a distinction between date and time (see YearMonthDayand DateTimeclasses).
我更喜欢直接使用Joda库 insetad of java.util.Date
,因为 Joda 区分日期和时间(参见YearMonthDay和DateTime类)。
However, if you do wish to use java.util.Date
I would suggest writing a utility method; e.g.
但是,如果您确实希望使用,java.util.Date
我建议您编写一个实用程序方法;例如
public static Date setTimeToMidnight(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime( date );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
回答by Jorn
If you really want to use the java.util.Date, you would do something like this:
如果你真的想使用 java.util.Date,你可以这样做:
public class TimeIgnoringComparator implements Comparator<Date> {
public int compare(Date d1, Date d2) {
if (d1.getYear() != d2.getYear())
return d1.getYear() - d2.getYear();
if (d1.getMonth() != d2.getMonth())
return d1.getMonth() - d2.getMonth();
return d1.getDate() - d2.getDate();
}
}
or, using a Calendar instead (preferred, since getYear() and such are deprecated)
或者,使用 Calendar 代替(首选,因为不推荐使用 getYear() 等)
public class TimeIgnoringComparator implements Comparator<Calendar> {
public int compare(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR))
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH))
return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
return c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
}
}
回答by Daniel C. Sobral
I too prefer Joda Time, but here's an alternative:
我也更喜欢Joda Time,但这里有一个替代方案:
long oneDay = 24 * 60 * 60 * 1000
long d1 = first.getTime() / oneDay
long d2 = second.getTime() / oneDay
d1 == d2
EDIT
编辑
I put the UTC thingy below in case you need to compare dates for a specific timezone other than UTC. If you do have such a need, though, then I really advise going for Joda.
如果您需要比较 UTC 以外的特定时区的日期,我将 UTC 放在下面。但是,如果您确实有这样的需求,那么我真的建议您选择 Joda。
long oneDay = 24 * 60 * 60 * 1000
long hoursFromUTC = -4 * 60 * 60 * 1000 // EST with Daylight Time Savings
long d1 = (first.getTime() + hoursFromUTC) / oneDay
long d2 = (second.getTime() + hoursFromUTC) / oneDay
d1 == d2
回答by Roland Tepp
I am afraid there is no method of comparing two dates that could be called "easy" or "simple".
恐怕没有可以称为“简单”或“简单”的比较两个日期的方法。
When comparing two time instances with any sort of reduced precision (e.g. just comparing dates), you must always take into account how time zone affects the comparison.
当比较两个具有任何降低精度的时间实例时(例如只比较日期),您必须始终考虑时区如何影响比较。
If date1
is specifying an event that occurred in +2 timezone and date2
is specifying an event that occurred in EST, for example, you must take care to properly understand the implications of the comparison.
例如,如果date1
指定发生在 +2 时区date2
的事件并指定发生在 EST 的事件,则必须注意正确理解比较的含义。
Is your purpose to figure out if the two events occurred in the same calendar date in their own respective time zones? Or do You need to know if the two dates fall into the same calendar date in a specific time zone (UTC or your local TZ, for example).
您的目的是要弄清楚这两个事件是否发生在各自时区的同一日历日期?或者您是否需要知道两个日期是否属于特定时区(例如 UTC 或您当地的 TZ)中的同一日历日期。
Once you figure out what it is actually that You are trying to compare, it is just a matter of getting the year-month-date triple in an appropriate time zone and do the comparison.
一旦您弄清楚您实际上要比较的是什么,只需在适当的时区中获取年月日三元组并进行比较即可。
Joda time might make the actual comparison operation look much cleaner, but the semantics of the comparison are still something You need to figure out yourself.
Joda time 可能会使实际的比较操作看起来更清晰,但是比较的语义仍然需要您自己弄清楚。
回答by Robert Brown
Any opinions on this alternative?
对这个替代方案有什么意见吗?
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));
回答by André
Apache commons-langis almost ubiquitous. So what about this?
Apache commons-lang几乎无处不在。那么这个呢?
if (DateUtils.isSameDay(date1, date2)) {
// it's same
} else if (date1.before(date2)) {
// it's before
} else {
// it's after
}
回答by Jean-Pierre Schnyder
My proposition:
我的提议:
Calendar cal = Calendar.getInstance();
cal.set(1999,10,01); // nov 1st, 1999
cal.set(Calendar.AM_PM,Calendar.AM);
cal.set(Calendar.HOUR,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
// date column in the Thought table is of type sql date
Thought thought = thoughtDao.getThought(date, language);
Assert.assertEquals(cal.getTime(), thought.getDate());
回答by technomama
This is what worked for me:
这对我有用:
var Date1 = new Date(dateObject1.toDateString()); //this sets time to 00:00:00
var Date2 = new Date(dateObject2.toDateString());
//do a normal compare
if(Date1 > Date2){ //do something }
回答by wilbert
Here is a solution from this blog: http://brigitzblog.blogspot.com/2011/10/java-compare-dates.html
这是此博客的解决方案:http: //brigitzblog.blogspot.com/2011/10/java-compare-dates.html
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
i.e. you can see if the time difference in milliseconds is less than the length of one day.
即您可以查看以毫秒为单位的时差是否小于一天的长度。