Jhon
Jhon

Reputation: 21

How to correct the exception: could not be parsed at index 0 in a conversion from string to OffsetDateTime?

I am trying to insert a date in the Oracle database using Spring Boot, I have a date as String in "20200723" format, then I try to convert it but when I try to convert to the entity that has a field type OffsetDateTime with a mapped it jumps an exception Text '20200723T00: 00: 00.00' could not be parsed at index 0. Thank you very much for your help.

Entity

      @Column(name = "of_date")
      private OffsetDateTime ofDate;

Mapper and method

        @Mapping(target = "ofDate", source = "kDto", qualifiedByName = 
        "ofDate")
        InTemp toEntity(KDto kDto);

        @Named("ofDate")
        default OffsetDateTime mapPostedDate(KDto kDto){
        LocalDateTime activationDate = LocalDateTime.parse(kDto.getOfDate() + 
        DEFAULT_TIME);
        return activationDate.atOffset(ZONE_OFF_SET_ACTIVATION_DATE);

Upvotes: 0

Views: 641

Answers (2)

Andreas
Andreas

Reputation: 159260

Don't add and parse the time part:

@Named("ofDate")
default OffsetDateTime mapPostedDate(KDto kDto) {
    return OffsetDateTime.of(LocalDate.parse(kDto.getOfDate()),
                             LocalTime.MIDNIGHT,
                             ZONE_OFF_SET_ACTIVATION_DATE);
}

Upvotes: 2

grekier
grekier

Reputation: 3726

You need to define a DateTimeFormatter and use it as your string is not the default

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH: mm: ss.SS");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Upvotes: 0

Related Questions