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
Susan SarandonOriginal
2024-11-28 18:35:10990browse

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"
    }
  }

When the desired format is:

"startDate": "2015-01-01"

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")

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

  1. Update application.properties:

    spring.jackson.serialization.write_dates_as_timestamps=false

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:
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