0

Hi i have two strings created from the simpleDateFormat type in java. They are as follows:

"dd/MM/yyyy hh:mm:ss a"

How can i compare two strings that have that format and know which is the latest?

jmj
  • 237,923
  • 42
  • 401
  • 438

2 Answers2

3

Follow these steps:

  1. Convert the 2 Strings to Date objects using the SimpleDateFormat. For more details on the conversion, you can refer this post.
    Example: Date date = new SimpleDateFormat(yourFormat).parse(dateString);
  2. Now compare the 2 Date objects using the Date#after() method.
Community
  • 1
  • 1
Rahul
  • 44,383
  • 11
  • 84
  • 103
1

You would want to convert the strings back into a Date object like so:

        SimpleDateFormat defaultDateFormat = new SimpleDateFormat"dd/MM/yyyy hh:mm:ss a", Locale.getDefault());
        Date myDate;
        try {
            myDate = defaultDateFormat.parse("insert your date/time string here");
        } catch (ParseException e) {
            ...
        }

and then use

myDate.compareTo(myOtherDate)

to figure out which date is greater. the compareTo() method returns a -1,0, or 1 depending on which date is the latest.

Simon
  • 26
  • 3