Spring Boot JSON Date format


By default, Spring Boot uses the ISO-8601 format for serializing java.time objects, including LocalDateTime, LocalDate, and ZonedDateTime. This format is a standard way of representing date and time information in JSON, and looks like this: "2023-05-01T15:23:45.123Z".

If you want to customize the date format used for JSON serialization of java.time objects in Spring Boot, you can do so by configuring a Jackson2ObjectMapperBuilder bean in your application configuration.

Here’s an example of how to customize the date format in Spring Boot using a Jackson2ObjectMapperBuilder:

import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
import org.springframework.http.converter.json.*;
import org.springframework.web.servlet.config.annotation.*;
import java.time.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.*;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.simpleDateFormat("dd/MM/yyyy HH:mm:ss");
        builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
        builder.serializers(new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}

In this example, we are configuring a custom Jackson2ObjectMapperBuilder bean that sets the date format to “dd/MM/yyyy HH:mm:ss”. We are also adding custom LocalDateTimeSerializer and ZonedDateTimeSerializer instances that use this date format. Finally, we add this MappingJackson2HttpMessageConverter to the list of HTTP message converters used by Spring MVC.

Now, when Spring Boot serializes java.time objects to JSON, it will use the custom date format specified in the Jackson2ObjectMapperBuilder.