java.time.format.DateTimeParseException: Text 'Thursday 30 May 2019 - 02:00 PM' could not be parsed at index 0

Viewed 2513

I need to convert the string "Thursday 30 May 2019 - 02:00 PM" to (dd MMM hh:mm a) DateTimeFormat "06 June 01:54 PM"(date).

Here is my code:

// last update date is : Thursday 30 May 2019 - 02:00 PM 
String lastUpadte WebUI.getText(findTestObject("Stock prices/date time"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate date = LocalDate.parse(lastUpadte, formatter);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>" + date);

enter image description here

2 Answers

The dates and times were revamped for Java 8, introducing types like LocalDateTime which are very easy to use. The lack of a year in one of your date strings is an added complexity, but using these features, you could have :

    String dtStr1 = "06 June 01:54 PM"; 
    DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
            .appendPattern("dd MMMM hh:mm a")
            .parseDefaulting(ChronoField.YEAR, 2019)
            .toFormatter();
    LocalDateTime date1 = LocalDateTime.parse(dtStr1, formatter1);

    String dtStr2 = "Thursday 30 May 2019 - 02:00 PM";  
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("EEEE dd MMM uuuu - hh:mm a");
    LocalDateTime date2 = LocalDateTime.parse(dtStr2, formatter2);

    System.out.println(date1);
    System.out.println(date2);

Output is :

2019-06-06T13:54 2019-05-30T14:00

The formatter patterns are listed in : https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

To get a java.time.LocalDateTime with the same format as "Thursday 30 May 2019 - 02:00 PM":

LocalDateTime ldt = LocalDateTime.parse("Thursday 30 May 2019 - 02:00 PM", 
        DateTimeFormatter.ofPattern("EEEE dd MMMM uuuu '-' hh':'mm a")));

For those with the same format as "06 June 01:54 PM":

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
   .appendPattern("dd MMMM hh':'mm a")
   .parseDefaulting(ChronoField.YEAR, 2019)
   .toFormatter();
LocalDateTime ldt = LocalDateTime.parse("06 June 01:54 PM", formatter)); 

Note we need to specifically build the parser this way in the latter example since the year is missing, otherwise we'll get an Exception.

Related