tags:

views:

412

answers:

7

I have two dates:

  1. toDate (user input in MM/dd/yyyy format)
  2. currentDate (obtained by 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?

+1  A: 

Date#equals() and Date#after()

If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 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.

Bozho
Given that Date.equals() will be comparing milliseconds and he's comparing the current date to MM/dd/yyyy user input, that's not really a productive approach.
BlairHippo
He wants to compare not check equality.
tkr
yes, thanks, I added the `after` method
Bozho
If he's converting user-input MM/dd/yyyy data into a Date object, wouldn't the effective time on that object be 0:00 that morning? Please correct me if I'm wrong, but it seems to me this approach will fail if the user enters today's date.
BlairHippo
Yes, but equals() is based on the milliseconds; aren't before() and after() based on it as well? If toDate is based on MM/dd/yyyy input, he'll also need to manually set the time to one millisecond before midnight of the next day; otherwise, this approach is going to fail if the user enters today's date. (Won't it?)
BlairHippo
Using Date considered bad practice? By whom?
COME FROM
@COME FROM: By Sun. Check the API; all but the simplest methods are deprecated.
BlairHippo
@BlairHippo: I know about the deprecation and I definitely recognize some of the design flaws of Date. However, you don't need to use the deprecated methods to use the class. The class itself is not deprecated.
COME FROM
A: 

Use java.util.Calendar if you have extensive date related processing.

Date has before(), after() methods. you could use them as well.

Vaishak Suresh
+2  A: 

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.

tkr
Please correct me if I'm wrong, but won't this fail if the user enters today's date? "new Date()" will set the time to whenever it's called, and a Date object based on MM/dd/yyyy will effectively be 0:00 that morning. Or are Date.before() and Date.after() not based on milliseconds the way Date.equals() is?
BlairHippo
That's right. Actually you have to use Calendar or a DateFormatter to get rid of time in java.util.Date.
tkr
+2  A: 

it is easier to compare dates using the java.util.Calendar . Here is what you might do:

Calendar toDate = Calendar.getInstance();
        Calendar nowDate = Calendar.getInstance();
        toDate.set(<set-year>,<set-month>,<set-date->);  
        if(!toDate.before(nowDate))
        //display your report
        else
        // don't display the report
Abdel Olakara
Question: would you need to explicitly clear the hour/minute/etc. fields out of nowDate, or does the fact that they're not set in toDate mean they don't matter?
BlairHippo
+1 for using calendar. If you're not comparing down near the millisecond level, you usually want to clear() the calendar immediately after you create it, then call the set method.
Ophidian
+3  A: 

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:

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.

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
    }
R. Bemrose
Fixed some bugs in this... forgot to catch the `ParseException` in the original version.
R. Bemrose
+1  A: 

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:

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.");
}
BalusC
A: 

If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:


    // 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.

BlairHippo