32

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?

Jason S
  • 184,598
  • 164
  • 608
  • 970
minil
  • 6,895
  • 16
  • 48
  • 55
  • 1
    Your initial question was honestly said terrible. I've improved it. In the future try to be as clear as possible. Don't repeat things 3 times and/or unnecessarily bold out things :) – BalusC May 11 '10 at 13:57
  • 3
    this could help if you consider using joda library http://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion – ukanth May 11 '10 at 14:16
  • JodaTime offers so much more than Java's Date API ... http://joda-time.sourceforge.net/. It would make this and your other date tasks much easier. – harschware May 11 '10 at 14:21

9 Answers9

21

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-day>);  
if(!toDate.before(nowDate)) {
    //display your report
} else {
    // don't display the report
}
erakitin
  • 11,437
  • 5
  • 44
  • 49
Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
  • 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 May 11 '10 at 13:52
  • 2
    +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 May 11 '10 at 15:40
  • i wonder why this isn't accepted yet – aLL Jun 24 '19 at 06:01
11

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
    }
Powerlord
  • 87,612
  • 17
  • 125
  • 175
6

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
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 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 May 11 '10 at 13:45
  • He wants to compare not check equality. – tkr May 11 '10 at 13:48
  • yes, thanks, I added the `after` method – Bozho May 11 '10 at 13:53
  • 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 May 11 '10 at 13:59
  • 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 May 11 '10 at 14:09
  • Using Date considered bad practice? By whom? – COME FROM May 11 '10 at 15:43
  • @COME FROM: By Sun. Check the API; all but the simplest methods are deprecated. – BlairHippo May 11 '10 at 17:34
  • @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 May 11 '10 at 19:06
5

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
  • 1,331
  • 1
  • 9
  • 27
  • 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 May 11 '10 at 14:05
  • That's right. Actually you have to use Calendar or a DateFormatter to get rid of time in java.util.Date. – tkr May 11 '10 at 14:35
5

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
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Mark Z
  • 31
  • 2
2
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 .

Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
Viren Savaliya
  • 520
  • 1
  • 6
  • 18
1

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
  • 9,502
  • 10
  • 54
  • 78
0

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

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

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66