比较Java中的两个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3144387/
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
Compare two dates in Java
提问by Gnaniyar Zubair
I need to compare two dates in java. I am using the code like this:
我需要在java中比较两个日期。我正在使用这样的代码:
Date questionDate = question.getStartDate();
Date today = new Date();
if(today.equals(questionDate)){
System.out.println("Both are equals");
}
This is not working. The content of the variables is the following:
这是行不通的。变量的内容如下:
questionDate
contains2010-06-30 00:31:40.0
today
containsWed Jun 30 01:41:25 IST 2010
questionDate
包含2010-06-30 00:31:40.0
today
包含Wed Jun 30 01:41:25 IST 2010
How can I resolve this?
我该如何解决这个问题?
采纳答案by Eric Hauser
Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date()
will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:
日期相等取决于两个日期等于毫秒。使用创建新的 Date 对象new Date()
永远不会等于过去创建的日期。Joda Time的 API 简化了日期的处理;但是,单独使用 Java 的 SDK:
if (removeTime(questionDate).equals(removeTime(today))
...
public Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
回答by CoolBeans
I would use JodaTime for this. Here is an example - lets say you want to find the difference in days between 2 dates.
我会为此使用 JodaTime。这是一个示例 - 假设您要查找 2 个日期之间的天数差异。
DateTime startDate = new DateTime(some_date);
DateTime endDate = new DateTime(); //current date
Days diff = Days.daysBetween(startDate, endDate);
System.out.println(diff.getDays());
JodaTime can be downloaded from here.
JodaTime 可以从这里下载。
回答by GreenMatt
It's not clear to me what you want, but I'll mention that the Dateclass also has a compareTomethod, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:
我不清楚你想要什么,但我会提到Date类还有一个compareTo方法,该方法可用于通过一次调用确定两个 Date 对象是否相等或(如果它们不相等)发生的情况早点。这允许您执行以下操作:
switch (today.compareTo(questionDate)) {
case -1: System.out.println("today is sooner than questionDate"); break;
case 0: System.out.println("today and questionDate are equal"); break;
case 1: System.out.println("today is later than questionDate"); break;
default: System.out.println("Invalid results from date comparison"); break;
}
It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.
应该注意的是,API 文档不保证结果为 -1、0 和 1,因此您可能希望在任何生产代码中使用 if-elses 而不是 switch。此外,如果第二个日期为空,您将收到 NullPointerException,因此将您的代码包装在 try-catch 中可能会很有用。
回答by Krolique
Here's what you can do for say yyyy-mm-dd comparison:
以下是您可以为 yyyy-mm-dd 比较做的事情:
GregorianCalendar gc= new GregorianCalendar();
gc.setTimeInMillis(System.currentTimeMillis());
gc.roll(GregorianCalendar.DAY_OF_MONTH, true);
Date d1 = new Date();
Date d2 = gc.getTime();
SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
if(sf.format(d2).hashCode() < sf.format(d1).hashCode())
{
System.out.println("date 2 is less than date 1");
}
else
{
System.out.println("date 2 is equal or greater than date 1");
}
回答by user569712
The following will return true if two Calendar variables have the same day of the year.
如果两个 Calendar 变量在一年中的同一天,则以下将返回 true。
public boolean isSameDay(Calendar c1, Calendar c2){
final int DAY=1000*60*60*24;
return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
} // end isSameDay
回答by Jamal
The easiest way to compare two dates is converting them to numeric value (like unix timestamp).
比较两个日期的最简单方法是将它们转换为数值(如 unix 时间戳)。
You can use Date.getTime()
method that return the unix time.
您可以使用Date.getTime()
返回 unix 时间的方法。
Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
System.out.println("Both are equals");
}
回答by Jamal
Here is an another answer: You need to format the tow dates to fit the same fromat to be able to compare them as string.
这是另一个答案:您需要格式化两个日期以适应相同的 fromat 以便能够将它们作为字符串进行比较。
Date questionDate = question.getStartDate();
Date today = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat ("yyyy/MM/dd");
String questionDateStr = dateFormatter.format(questionDate);
String todayStr = dateFormatter.format(today);
if(questionDateStr.equals(todayStr)) {
System.out.println("Both are equals");
}
回答by harsha.kuruwita
it is esy using time.compareTo(currentTime) < 0
很容易使用 time.compareTo(currentTime) < 0
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask {
static Timer singleTask = new Timer();
@SuppressWarnings("deprecation")
public static void main(String args[]) {
// set download schedule time
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 54);
calendar.set(Calendar.SECOND, 0);
Date time = (Date) calendar.getTime();
// get current time
Date currentTime = new Date();
// if current time> time schedule set for next day
if (time.compareTo(currentTime) < 0) {
time.setDate(time.getDate() + 1);
} else {
// do nothing
}
singleTask.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("timer task is runing");
}
}, time);
}
}
回答by yurin
public static double periodOfTimeInMillis(Date date1, Date date2) {
return (date2.getTime() - date1.getTime());
}
public static double periodOfTimeInSec(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 1000;
}
public static double periodOfTimeInMin(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 1000);
}
public static double periodOfTimeInHours(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}
public static double periodOfTimeInDays(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}
回答by PT_C
public long compareDates(Date exp, Date today){
long b = (exp.getTime()-86400000)/86400000;
long c = (today.getTime()-86400000)/86400000;
return b-c;
}
This works for GregorianDates.
86400000 are the amount of milliseconds in a day, this will return the number of days between the two dates.
这适用于GregorianDates.
86400000 是一天中的毫秒数,这将返回两个日期之间的天数。