Reputation: 8166
I need to compare two dates in java. I am using the code like this:
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
contains 2010-06-30 00:31:40.0
today
contains Wed Jun 30 01:41:25 IST 2010
How can I resolve this?
Upvotes: 25
Views: 103609
Reputation: 170
In Java 8 there is no need to use Joda-Time as it comes with a similar new API in the java.time
package. Use the LocalDate
class.
LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate today = LocalDate.now();
Boolean isToday = date.isEqual( today );
You can ask for the span of time between the dates with Period
class.
Period difference = Period.between(date, today);
LocalDate
is comparable using equals
and compareTo
as it holds no information about Time and Timezone.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project 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.
Upvotes: 5
Reputation: 428
It works best....
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
Upvotes: 0
Reputation: 5581
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:
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();
}
Upvotes: 42
Reputation: 347
in my case, I just had to do something like this :
date1.toString().equals(date2.toString())
And it worked!
Upvotes: 0
Reputation: 179
This is a very old post though sharing my work. Here is a little trick to do so
DateTime dtStart = new DateTime(Dateforcomparision);
DateTime dtNow = new DateTime(); //current date
if(dtStart.getMillis() <= dtNow.getMillis())
{
//to do
}
use comparator as per your requirement
Upvotes: 0
Reputation: 6087
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);
}
Upvotes: 0
Reputation: 1331
it is esy using 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);
}
}
Upvotes: 3
Reputation: 69
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.
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");
}
Upvotes: 0
Reputation: 69
The easiest way to compare two dates is converting them to numeric value (like unix timestamp).
You can use Date.getTime()
method that return the unix time.
Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
System.out.println("Both are equals");
}
Upvotes: 5
Reputation: 11
The following will return true if two Calendar variables have the same day of the year.
public boolean isSameDay(Calendar c1, Calendar c2){
final int DAY=1000*60*60*24;
return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
} // end isSameDay
Upvotes: 1
Reputation: 682
Here's what you can do for say yyyy-mm-dd comparison:
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");
}
Upvotes: -1
Reputation: 18570
It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, 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:
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.
Upvotes: 10
Reputation: 20800
I would use JodaTime for this. Here is an example - lets say you want to find the difference in days between 2 dates.
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.
Upvotes: 13