Home > Java > javaTutorial > How to Properly Format Java 8 LocalDateTime in Spring Boot JSON Responses?

How to Properly Format Java 8 LocalDateTime in Spring Boot JSON Responses?

Susan Sarandon
Release: 2024-11-28 18:35:10
Original
1010 people have browsed it

How to Properly Format Java 8 LocalDateTime in Spring Boot JSON Responses?

JSON Java 8 LocalDateTime Format in Spring Boot

When dealing with Java 8's LocalDateTime in a Spring Boot application, it's common to face formatting challenges. In this article, we'll examine the issue and provide a solution.

Issue

Some users report that LocalDateTime objects are being converted into an unconventional format:

"startDate" : {
    "year" : 2010,
    "month" : "JANUARY",
    "dayOfMonth" : 1,
    "dayOfWeek" : "FRIDAY",
    "dayOfYear" : 1,
    "monthValue" : 1,
    "hour" : 2,
    "minute" : 2,
    "second" : 0,
    "nano" : 0,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
Copy after login

When the desired format is:

"startDate": "2015-01-01"
Copy after login

Despite annotations such as @JsonFormat and @DateTimeFormat, the formatting issue persists.

Solution

In order to achieve the desired format, we need to take the following steps:

  1. Add the following dependency:

    compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
    Copy after login

This dependency provides a converter for Java 8 date and time types.

  1. Update application.properties:

    spring.jackson.serialization.write_dates_as_timestamps=false
    Copy after login

This setting ensures that the converter is used and dates are formatted in the desired format.

  1. Use annotations for custom formatting (optional):
    If you wish to further customize the formatting, you can use annotations like @JsonFormat and @DateTimeFormat. However, these annotations are only necessary if you want to change the default format.

The above is the detailed content of How to Properly Format Java 8 LocalDateTime in Spring Boot JSON Responses?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template