如何比较Java中的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2592501/
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 dates in Java?
提问by ant
How do I compare dates in between in Java?
如何在Java中比较两者之间的日期?
Example:
例子:
date1 is 22-02-2010
date2 is 07-04-2010
today
date3 is 25-12-2010
date1 是22-02-2010
date2 是07-04-2010
今天
date3 是25-12-2010
date3
is always greater than date1
and date2
is always today. How do I verify if today's date is in between date1 and date 3?
date3
总是大于date1
和date2
今天始终。如何验证今天的日期是否在日期 1 和日期 3 之间?
采纳答案by Bart Kiers
Datehas beforeand aftermethods and can be compared to each otheras follows:
Date有before和after方法,可以按如下方式相互比较:
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-Timea go, but note that:
你也可以试试Joda-Time,但请注意:
Joda-Time is the de factostandard 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。
回答by sam
Compare the two dates:
比较两个日期:
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
System.out.println("My Date is"+myDate);
System.out.println("Today Date is"+today);
if (today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if (today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
回答by Everyone
Use getTime() to get the numeric value of the date, and then compare using the returned values.
使用 getTime() 获取日期的数值,然后使用返回值进行比较。
回答by Brownsoo Han
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
}
回答by Sunil Kumar Sahoo
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");
}
回答by Basil Bourque
tl;dr
tl;博士
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-Extralibrary to your project.
或者,更好的是,如果您将ThreeTen-Extra库添加到您的项目中。
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusivewhile 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 8601formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
顺便说一句,对于日期或日期时间值的文本表示,这是一个错误的格式选择。只要有可能,就坚持使用标准的ISO 8601格式。ISO 8601 格式是明确的,可以跨人类文化理解,并且易于机器解析。
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
对于仅限日期的值,标准格式为 YYYY-MM-DD。请注意这种格式在按字母顺序排序时如何具有按时间顺序排列的好处。
LocalDate
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 Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
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 inclusivewhile the ending is exclusive. 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 gstackoverflowshowing the list of comparison methods you can call.
请参阅gstackoverflow 的答案,其中显示了您可以调用的比较方法列表。
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8and SE 9and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8和SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
更新:下面的“Joda-Time”部分作为历史完整保留。现在处于维护模式的Joda-Time项目建议迁移到java.time类。
Joda-Time
乔达时间
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time2.3 library.
关于捆绑的 java.util.Date 和 java.util.Calendar 类,其他答案是正确的。但这些课程是出了名的麻烦。所以这里有一些使用Joda-Time2.3 库的示例代码。
If you truly want a date without any time portion and no time zone, then use the LocalDate
class in Joda-Time. That class provides methods of comparison including compareTo
(used with Java Comparators), isBefore
, isAfter
, and isEqual
.
如果你真的想要一个没有任何时间部分和时区的日期,那么使用LocalDate
Joda-Time 中的类。该类提供了比较方法,包括compareTo
(与Java Comparator 一起使用)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. Methods such as overlap
and contains
make comparisons easy.
如果您处理时间跨度,我建议在 Joda-Time 中探索类:Duration、Interval和Period。诸如overlap
和 之类的方法contains
使比较变得容易。
For text representations, look at the ISO 8601 standard's:
对于文本表示,请查看 ISO 8601 标准:
- duration
Format: PnYnMnDTnHnMnS
Example: 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
- 持续时间
格式:PnYnMnDTnHnMnS
示例:P3Y6M4DT12H30M5S
(表示“三年六个月四天十二小时三十分钟五秒”) - 间隔
格式:开始/结束
示例: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-Openapproach where the beginning of the span is inclusivewhile the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
Joda-Time 使用Half-Open方法执行比较,其中 span 的开头是inclusive而结尾是Exclusive。这种方法是处理时间跨度的明智方法。搜索 StackOverflow 以获取更多信息。
回答by Salman A
You can use Date.getTime()
which:
您可以使用Date.getTime()
哪个:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由此 Date 对象表示的毫秒数。
This means you can compare them just like numbers:
这意味着您可以像数字一样比较它们:
if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
/*
* date is between date1 and date2 (both inclusive)
*/
}
/*
* when date1 = 2015-01-01 and date2 = 2015-01-10 then
* returns true for:
* 2015-01-01
* 2015-01-01 00:00:01
* 2015-01-02
* 2015-01-10
* returns false for:
* 2014-12-31 23:59:59
* 2015-01-10 00:00:01
*
* if one or both dates are exclusive then change <= to <
*/
回答by gstackoverflow
Update for Java 8 and later
Java 8 及更高版本的更新
These methods exists in LocalDate
, LocalTime
, and LocalDateTime
classes.
这些方法都存在LocalDate
,LocalTime
以及LocalDateTime
类。
Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Androidin ThreeTenABP(see How to use…).
这些类内置于 Java 8 及更高版本中。大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植,并进一步用于安卓在ThreeTenABP(见如何使用......)。
回答by Garambe
Try this
尝试这个
public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
Date date1 = dateFormat.parse(psDate1);
Date date2 = dateFormat.parse(psDate2);
if(date2.after(date1)) {
return true;
} else {
return false;
}
}