Search code examples
javadatetime-formatdatetime-comparison

How to convert two different string dates into a single date format


I have two strings that I want to convert into a particular date time format so I can do a comparison. Problem I have is that it errors out in the parse with an exception and I wonder if I am doing something wrong. Wanted to ask what is the best way to convert two different string dates into a single date format

SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy dd mm - HH:mm:ss");
        String firstDateString= "11 May 2018 21:03:51 GMT";
        String secondDateString= "dataStore.get("2018-05-11T21:03:51Z";

        Date firstDateFormat =localDateFormat.parse(firstDateString);
        Date secondDateFormat =localDateFormat.parse(secondDateString);

Solution

  • Problem I have is that it errors out in the parse with an exception and I wonder if I am doing something wrong.

    => Yes you are doing it actually. You first need to parse the date into it's actual format and then format it into the desired format.

    For example: for parsing and formatting 2018-05-11T21:03:51Z

    DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:MM:SS'z'", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat("yyyy dd mm - HH:mm:ss");
    Date date = originalFormat.parse("2018-05-11T21:03:51Z");
    String formattedDate = targetFormat.format(date);  // 2018 05 11 - 21:03:51