使用 Java 进行日期比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2811121/
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
Date Comparison using Java
提问by minil
I have two dates:
我有两个日期:
toDate
(user input inMM/dd/yyyy
format)currentDate
(obtained bynew Date()
)
toDate
(用户输入MM/dd/yyyy
格式)currentDate
(由 获得new Date()
)
I need to compare the currentDate
with toDate
. I have to display a report only when the toDate
is equal to or more than currentDate
. How can I do that?
我需要currentDate
与toDate
. 仅当toDate
等于或大于时,我才必须显示报告currentDate
。我怎样才能做到这一点?
回答by Bozho
If there is a possibility that the hour
and minute
fields are != 0, you'd have to set them to 0.
如果hour
和minute
字段可能为 != 0,则必须将它们设置为 0。
I can't forget to mention that using java.util.Date
is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar
or JodaTime, if possible.
我不能忘记提到使用java.util.Date
被认为是一种不好的做法,并且它的大部分方法都已弃用。如果可能,请使用java.util.Calendar
或JodaTime。
回答by Vaishak Suresh
Use java.util.Calendar
if you have extensive date related processing.
使用java.util.Calendar
,如果你有大量的日期相关的处理。
Date has before()
, after()
methods. you could use them as well.
日期有before()
,after()
方法。你也可以使用它们。
回答by tkr
You are probably looking for:
您可能正在寻找:
!toDate.before(currentDate)
before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.
before() 和 after() 测试日期是严格之前还是之后。因此,您必须否定另一个才能获得非严格行为。
回答by Abdel Raoof
It is easier to compare dates using the java.util.Calendar
.
Here is what you might do:
使用java.util.Calendar
. 以下是您可以执行的操作:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
回答by Powerlord
If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat
to convert the string to a Date, then compare the two using .equals:
如果您打算使用 Java 日期而不是 JodaTime,请使用 ajava.text.DateFormat
将字符串转换为日期,然后使用 .equals 比较两者:
I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar
object below to do it.
我差点忘了:在比较它们之前,您需要将当前日期的小时、分钟、秒和毫秒归零。我使用Calendar
下面的一个对象来做到这一点。
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
// Other code here
String toDate;
//toDate = "05/11/2010";
// Value assigned to toDate somewhere in here
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currDtCal = Calendar.getInstance();
// Zero out the hour, minute, second, and millisecond
currDtCal.set(Calendar.HOUR_OF_DAY, 0);
currDtCal.set(Calendar.MINUTE, 0);
currDtCal.set(Calendar.SECOND, 0);
currDtCal.set(Calendar.MILLISECOND, 0);
Date currDt = currDtCal.getTime();
Date toDt;
try {
toDt = df.parse(toDate);
} catch (ParseException e) {
toDt = null;
// Print some error message back to the user
}
if (currDt.equals(toDt)) {
// They're the same date
}
回答by BalusC
This is one of the ways:
这是其中一种方式:
String toDate = "05/11/2010";
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
A bit more easy interpretable:
更容易解释:
String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Oh, as a bonus, the JodaTime's variant:
哦,作为奖励,JodaTime的变体:
String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
回答by BlairHippo
If for some reason you're intent on using Date
objects for your solution, you'll need to do something like this:
如果出于某种原因,您打算在Date
解决方案中使用对象,则需要执行以下操作:
// Convert user input into year, month, and day integers
Date toDate = new Date(year - 1900, month - 1, day + 1);
Date currentDate = new Date();
boolean runThatReport = toDate.after(currentDate);
Shifting the toDate
ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date
will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate
off of new Date()
and then fiddle around with the year, month, and day, for instance). Use Calendar
, as described elsewhere.
将toDate
提前到第二天的午夜将解决我在其他答案的评论中抱怨的错误。但是,请注意,这种方法使用了不推荐使用的构造函数;任何方法依赖于Date
将使用一个过时的方法或另一种,取决于你怎么做就可能导致竞争条件,以及(如果你基地toDate
关闭的new Date()
,然后反复折腾的年,月,日,例如)。使用Calendar
,如别处所述。
回答by Mark Z
Date long getTime()
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
Date long getTime()
返回自此January 1, 1970, 00:00:00 GMT
Date 对象表示以来经过的毫秒数。
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
回答by Viren Savaliya
private boolean checkDateLimit() {
long CurrentDateInMilisecond = System.currentTimeMillis(); // Date 1
long Date1InMilisecond = Date1.getTimeInMillis(); //Date2
if (CurrentDateInMilisecond <= Date1InMilisecond) {
return true;
} else {
return false;
}
}
// Convert both date into milisecond value .
// 将两个日期都转换为毫秒值。