Search code examples
spring-mvcjacksondate-formatjackson-databind

Jackson deserialize LocalDateTime


I have a time field value like below :

2020-10-01T15:30:27.4394205+03:00

I can't figure it out how to represent as date Format.

i need to deserialize it to LocalDateTime field.

I have tried like this;

   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
    private LocalDateTime timestamp;

but it doesn't work. How can i deserialize it? I am using spring boot by the way. And this value coming to rest controller request body.


Solution

  • Replace the pattern as pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME

    Your date-time string is already in the format specified by DateTimeFormatter.ISO_OFFSET_DATE_TIME which is the default format used by OffsetDateTime#parse.

    Demo:

    import java.time.LocalDateTime;
    import java.time.OffsetDateTime;
    
    public class Main {
        public static void main(String[] args) {
            String dateTimeStr = "2020-10-01T15:30:27.4394205+03:00";
    
            // Parse the date-time string into OffsetDateTime
            OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
            System.out.println(odt);
    
            // LocalDateTime from OffsetDateTime
            LocalDateTime ldt = odt.toLocalDateTime();
            System.out.println(ldt);
        }
    }
    

    Output:

    2020-10-01T15:30:27.439420500+03:00
    2020-10-01T15:30:27.439420500