SpringBoot Jackson change timestamp format


To change the timestamp format used by Jackson when serializing dates and times to JSON, you can customize the ObjectMapper configuration used by Spring Boot.

By default, Jackson uses the ISO-8601 format for timestamps, which looks like this: "2023-05-01T15:23:45.123Z". However, you can use the @JsonFormat annotation to customize the format of timestamps in individual fields of your Java objects.

Here’s an example of how to customize the timestamp format used by Jackson globally in a Spring Boot application:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        return objectMapper;
    }
}

In this example, we create a JacksonConfig class annotated with @Configuration, and define a @Bean method that returns an instance of ObjectMapper. We then configure the ObjectMapper to disable the serialization of dates as timestamps (WRITE_DATES_AS_TIMESTAMPS), and set a custom date format that includes a colon in the time zone offset (withColonInTimeZone).

With this configuration in place, Jackson will use the custom date format specified by StdDateFormat to serialize dates and times to JSON.

Alternatively, if you want to customize the format for a specific field in your Java object, you can use the @JsonFormat annotation, like this:

import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;

public class MyObject {

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

    // getter and setter
}

In this example, we are using the @JsonFormat annotation to specify that the timestamp field should be serialized as a string, using the pattern "dd-MM-yyyy HH:mm:ss".