Facing problem while reading date time in java from excel by converting date into String Format then parsing it

Trying to store date time from excel to setter using poi and LocalDateTime and DateTimeFormatter.

    DateTimeFormatter format=DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss");
    LocalDateTime 
    dateObj=LocalDateTime.parse(row.getCell(2).getLocalDateTimeCellValue().toString(),format);
    dto.setDate(dateObj);

The output is:

    java.time.format.DateTimeParseException: Text '2023-01-22T00:00' could not be parsed at index 2

Please advise me what to do? In the excel file the date is stored in 1/22/2023 12:00:00 AM

>Solution :

You are using DateTimeFormatter for the wrong purpose. Instead of formatting a LocalDateTime object, you are trying to parse a string unnecessarily. You need a formatted String which you can do as follows:

LocalDateTime dateObj = row.getCell(2).getLocalDateTimeCellValue();
DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
String formatted = dateObj.format(format);

Learn more about the modern Date-Time API from Trail: Date Time.

Leave a Reply