how can i compare two simpledateformat types in java with the following spec "dd/MM/yyyy hh:mm:ss a"

StackOverflow https://stackoverflow.com/questions/23225687

  •  07-07-2023
  •  | 
  •  

Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top