Master Global Date Formatting in Spring Boot: Simple Tips
This article explains how to achieve consistent date and time formatting in Spring Boot applications by using SimpleDateFormat, configuring Jackson globally with spring.jackson properties, and applying @JsonFormat, @JsonComponent, and @Configuration annotations to handle various Java date types efficiently.
Formatting dates is a frequent requirement in Java backend projects, especially when API responses contain date fields that need a specific presentation.
Using SimpleDateFormat works for individual conversions but leads to repetitive code and only affects java.util.Date types.
Spring Boot allows global date formatting via spring.jackson.date-format and spring.jackson.time-zone properties, but this configuration only applies to java.util.Date objects.
@JsonFormat Annotation
The @JsonFormat annotation can be placed on entity fields to define locale, timezone, and pattern, providing precise control over the serialization of LocalDateTime and Date fields.
@Data
public class OrderDTO {
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
private LocalDateTime createTime;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}@JsonComponent Annotation (Recommended)
For a true global solution, define a custom component with @JsonComponent that provides serializers and deserializers for both Date and LocalDate types.
@JsonComponent
public class DateFormatConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat(pattern);
df.setTimeZone(tz);
return builder -> builder
.failOnEmptyBeans(false)
.failOnUnknownProperties(false)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.dateFormat(df);
}
@Bean
public LocalDateTimeSerializer localDateTimeSerializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
}
}@Configuration Annotation
An alternative global configuration uses a @Configuration class that registers a JavaTimeModule with custom serializers for LocalDateTime and deserializers for Date. Note that after applying this configuration, field‑level @JsonFormat annotations are ignored.
@Configuration
public class DateFormatConfig2 {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Bean
@Primary
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
// Serializer and deserializer implementations omitted for brevity
}In summary, combining global configuration with selective @JsonFormat usage enables concise and consistent date handling across a Spring Boot application, reducing boilerplate and improving code readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
