I need to get the current date in the format MM/DD/YYYY and compare it to another string in the same format to see if the current date is greater than the string date. What is the best way of doing this? thanks.

Recommended Answers

All 4 Replies

By using SimpleDateFormat to parse the "String" into a date, then compare the two Date objects.

I figured out how to parse the String into a date object with the formatting "MM/dd/yyyy". This is what I have so far:

Date dtest = new SimpleDateFormat("MM/dd/yyyy").parse(letterdate);

where letterdate is the string.

Now I need to get a date object of the current date in the same format ("MM/dd/yyyy") and compare the two date objects to see which one is greater. How would I do this? thanks.

Couple of ways to do that

try {
    Calendar calThen = new GregorianCalendar();
    calThen.setTime(new SimpleDateFormat("MM/dd/yyyy").parse("12/15/2003"));
    Calendar calNow = Calendar.getInstance();
    System.out.println("After = "+calNow.after(calThen));

    Date dateThen = new SimpleDateFormat("MM/dd/yyyy").parse("12/15/2003");
    Date dateNow = new Date();
    System.out.println("After = "+dateNow.after(dateThen));
} catch(ParseException ex) {
    ex.printStackTrace();
}

Calendar is the intended way these days, since Date is deprecated. But the whole Date / Calendar API is still somewhat of an awkward mess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.