Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll show how to format JSON date fields in a Spring Boot application.

We’ll explore various ways of formatting dates using Jackson, which Spring Boot uses as its default JSON processor.

2. Using @JsonFormat on a Date Field

2.1. Setting the Format

We can use the @JsonFormat annotation to format a specific field:

public class Contact {

    // other fields

    @JsonFormat(pattern="yyyy-MM-dd")
    private LocalDate birthday;
     
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastUpdate;

    // standard getters and setters

}

On the birthday field, we use a pattern that renders only the date, while on the lastUpdate field, we also include the time.

We used the Java 8 date types, which are quite handy for dealing with temporal types.

Of course, if we need to use the legacy types such as java.util.Date, we can use the annotation in the same way:

public class ContactWithJavaUtilDate {

     // other fields

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date birthday;
     
     @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
     private Date lastUpdate;

     // standard getters and setters
}

Finally, let’s take a look at the output rendered by using the @JsonFormat with the given date format:

{
    "birthday": "2019-02-03",
    "lastUpdate": "2019-02-03 10:08:02"
}

As we can see, using the @JsonFormat annotation is an excellent way to format a particular date field.

However, we should only use it when we need specific formatting for fields. If we want to have a general format for all dates in our application, there are better ways to achieve this as we’ll see later.

2.2. Setting the Time Zone

If we need to use a particular time zone, we can set the timezone attribute of the @JsonFormat:

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Zagreb")
private LocalDateTime lastUpdate;

We don’t need to use it if a type already contains the time zone, for example, with java.time.ZonedDatetime.

3. Configuring the Default Format

While @JsonFormat is powerful on its own, hard-coding the format and time zone can bite us down the road.

If we want to configure a default format for all dates in our application, a more flexible way is to configure it in application.properties:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

And if we want to use a specific time zone in our JSON dates, there’s also a property for that:

spring.jackson.time-zone=Europe/Zagreb

Although setting the default format like this is quite handy and straightforward, there’s a drawback to this approach. Unfortunately, it doesn’t work with the Java 8 date types, such as LocalDate and LocalDateTime. We can only use it to format fields of the type java.util.Date or the java.util.CalendarThere is hope, though, as we’ll soon see.

4. Customizing Jackson’s ObjectMapper

So, if we want to use Java 8 date types and set a default date format, we need to look at creating a Jackson2ObjectMapperBuilderCustomizer bean:

@Configuration
public class ContactAppConfig {

    private static final String dateFormat = "yyyy-MM-dd";
    private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat(dateTimeFormat);
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
        };
    }

}

The above example shows how to configure a default format in our application. We have to define a bean and override its customize method to set the desired format.

Although this approach might look a bit cumbersome, the nice thing is that it works for both the Java 8 and the legacy date types.

5. Conclusion

In this article, we explored a number of ways to format JSON dates in a Spring Boot application.

As always, the source code for the examples can be found over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!