1

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

  • What does `.getLocalDateTimeCellValue()` do? What's the return type? If you receive `LocalDateTime` from `.getLocalDateTimeCellValue()` then what you are trying to do doesn't make any sense. – Serg Vasylchak Jan 18 '23 at 18:22
  • getLocalDateTimeCellValue() returns LocalDateTime object from a excel cell value – Tathagata Dasgupta Jan 18 '23 at 18:25
  • 4
    What you are trying to do doesn't make any sense if dto#date is of type `LocalDateTime`. LocalDateTime doesn't store any preferable format, but only stores the value (LocalDate and LocalTime). When you do `.getLocalDateTimeCellValue().toString()` you basically transform `LocalDateTime` to `String` with default ISO formatter and then again try to transform it into the `LocalDateTime`. – Serg Vasylchak Jan 18 '23 at 18:32

1 Answers1

3

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I want to store it in MM/dd/yyyy hh:mm:ss format in pojo class object, same as excel data – Tathagata Dasgupta Jan 18 '23 at 18:27
  • @TathagataDasgupta - I got confused initially thinking that you wanted to parse a string. I have updated my answer as per your requirement. – Arvind Kumar Avinash Jan 18 '23 at 18:32
  • 3
    @TathagataDasgupta No you don’t. You want to use the correct data type in your POJO, that is, `LocalDateTime`. You want to format it in your user interface, not in your data model. – Ole V.V. Jan 18 '23 at 18:32