本文翻译自:How to compare dates in Java? [duplicate]
How do I compare dates in between in Java? 如何在Java之间比较日期?
Example: 例:
date1 is 22-02-2010
date1是22-02-2010
date2 is 07-04-2010
today date2是今天的07-04-2010
date3 is 25-12-2010
date3是25-12-2010
date3
is always greater than date1
and date2
is always today. date3
始终大于date1
, date2
始终是今天。 How do I verify if today's date is in between date1 and date 3? 如何验证今天的日期是否在date1和date 3之间?
#1楼
参考:https://stackoom.com/question/AsQX/如何在Java中比较日期-重复
#2楼
This code determine today is in some duration.. based on KOREA locale 这段代码确定今天是在一定时期内..基于韩国语言环境
Calendar cstart = Calendar.getInstance(Locale.KOREA);
cstart.clear();
cstart.set(startyear, startmonth, startday);
Calendar cend = Calendar.getInstance(Locale.KOREA);
cend.clear();
cend.set(endyear, endmonth, endday);
Calendar c = Calendar.getInstance(Locale.KOREA);
if(c.after(cstart) && c.before(cend)) {
// today is in startyear/startmonth/startday ~ endyear/endmonth/endday
}
#3楼
Following are most common way of comparing dates. 以下是比较日期的最常用方法。 But I have prefer first one 但我更喜欢第一个
Approach-1 : Using Date.before(), Date.after() and Date.equals() 方法1:使用Date.before(),Date.after()和Date.equals()
if(date1.after(date2)){
System.out.println("Date1 is after Date2");
}
if(date1.before(date2)){
System.out.println("Date1 is before Date2");
}
if(date1.equals(date2)){
System.out.println("Date1 is equal Date2");
}
Approach-2 : Date.compareTo() 方法2:Date.compareTo()
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else{
System.out.println("Date1 is equal to Date2");
}
Approach-3 : Calender.before(), Calender.after() and Calender.equals() 方法3:Calender.before(),Calender.after()和Calender.equals()
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if(cal1.after(cal2)){
System.out.println("Date1 is after Date2");
}
if(cal1.before(cal2)){
System.out.println("Date1 is before Date2");
}
if(cal1.equals(cal2)){
System.out.println("Date1 is equal Date2");
}
#4楼
tl;dr tl; dr
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project. 或者,如果将ThreeTen-Extra库添加到项目中,则更好。
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive . 半开放式方法,其中开始是包含在内的,而结束是排斥的 。
Bad Choice of Format 格式错误选择
By the way, that is a bad choice of format for a text representation of a date or date-time value. 顺便说一句,对于日期或日期-时间值的文本表示,这是格式的错误选择。 Whenever possible, stick with the standard ISO 8601 formats. 尽可能使用标准的ISO 8601格式。 ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine. ISO 8601格式是明确的,在整个人类文化中都是可以理解的,并且易于通过机器进行解析。
For a date-only value, the standard format is YYYY-MM-DD. 对于仅日期的值,标准格式为YYYY-MM-DD。 Note how this format has the benefit of being chronological when sorted alphabetically. 请注意,按字母顺序排序时,这种格式的好处是按时间顺序排列。
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone. LocalDate
类表示没有日期和时区的仅日期值。
A time zone is crucial in determining a date. 时区对于确定日期至关重要。 For any given moment, the date varies around the globe by zone. 在任何给定时刻,日期都会在全球范围内变化。 For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec . 例如, 法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match. 由于您的输入字符串是非标准格式,因此我们必须定义一个格式匹配的格式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings. 使用它来解析输入字符串。
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive . 在日期时间工作中,通常最好使用Half-Open方法定义时间范围,其中开始是包含在内的,而结尾是排除的 。 So we want to know if today is the same or later than the start and also before the stop. 因此,我们想知道今天是否等于或晚于开始时间,以及是否晚于停止时间。 A briefer way of saying “is the same or later than the start” is “not before the start”. 简短地说“等于或晚于开始”是“不在开始之前”。
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call. 请参见gstackoverflow的答案,其中显示了可以调用的比较方法的列表。
About java.time 关于java.time
The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
. 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.Date
, Calendar
和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 。 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310 。
Where to obtain the java.time classes? 在哪里获取java.time类?
- Java SE 8 and SE 9 and later Java SE 8和SE 9及更高版本
- Built-in. 内置的
- Part of the standard Java API with a bundled implementation. 标准Java API的一部分,具有捆绑的实现。
- Java 9 adds some minor features and fixes. Java 9添加了一些次要功能和修复。
- Java SE 6 and SE 7 Java SE 6和SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7。
- Android 安卓系统
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically. ThreeTenABP项目专门针对Android改编了ThreeTen-Backport (如上所述)。
- See How to use ThreeTenABP… . 请参阅如何使用ThreeTenABP… 。
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more . 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
UPDATE: This “Joda-Time” section below is left intact as history. 更新:下面的“ Joda-Time”部分保留为历史记录。 The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
Joda-Time 乔达时代
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. 对于捆绑的java.util.Date和java.util.Calendar类,其他答案是正确的。 But those classes are notoriously troublesome. 但是众所周知,这些课程很麻烦。 So here's some example code using the Joda-Time 2.3 library. 因此,这是使用Joda-Time 2.3库的一些示例代码。
If you truly want a date without any time portion and no time zone, then use the LocalDate
class in Joda-Time. 如果您确实想要一个没有任何时间部分且没有时区的日期,请使用Joda-Time中的LocalDate
类。 That class provides methods of comparison including compareTo
(used with Java Comparators ), isBefore
, isAfter
, and isEqual
. 该类提供了比较方法,包括compareTo
(与Java Comparators一起使用 ), isBefore
, isAfter
和isEqual
。
Inputs… 输入...
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings… 定义描述输入字符串的格式化程序…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects… 使用格式化程序将字符串解析为LocalDate对象…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console… 转储到控制台...
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run… 运行时...
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)… 因此,看看第二个是否在其他两个之间(排他性地,意味着不等于任何一个端点)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
Working With Spans Of Time 处理时间跨度
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration , Interval , and Period . 如果您使用时间跨度,建议您在Joda-Time中探索以下类: Duration , Interval和Period 。 Methods such as overlap
and contains
make comparisons easy. overlap
和contains
使比较变得容易。
For text representations, look at the ISO 8601 standard's: 对于文本表示,请查看ISO 8601标准:
- duration 持续时间
Format: PnYnMnDTnHnMnS 格式:PnYnMnDTnHnMnS
Example: P3Y6M4DT12H30M5S 示例:P3Y6M4DT12H30M5S
(Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”) (表示“三年零六个月零四天十二小时三十分钟五秒”) - interval 间隔
Format: start/end 格式:开始/结束
Example: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z 示例:2007-03-01T13:00:00Z / 2008-05-11T15:30:00Z
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings). Joda-Time类可以同时使用这两种格式的字符串,既可以作为输入(解析),也可以作为输出(生成字符串)。
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive . Joda-Time使用Half-Open方法进行比较,其中跨度的开始是包含在内的,而结束是排他的 。 This approach is a wise one for handling spans of time. 这种方法是处理时间跨度的明智选择。 Search StackOverflow for more info. 搜索StackOverflow以获取更多信息。
#5楼
Date has before and after methods and can be compared to each other as follows: 日期有之前和之后的方法,可以相互比较 ,如下所示:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison: 进行包容性比较:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that: 您也可以尝试一下Joda-Time ,但请注意:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time ( JSR-310 ). Joda-Time是Java SE 8之前的Java的事实上的标准日期和时间库。现在,要求用户迁移到java.time ( JSR-310 )。
Back-ports are available for Java 6 and 7 as well as Android. 反向端口适用于Java 6和7以及Android。
#6楼
使用compareTo :
date1.compareTo(date2);