Convert java.util.Date to json format

12,253

RestEasy supports JSON via Jackson, so you can handle Date serialization in several ways.

1. @JsonFormat annotation

If you want to format specific field - simply add @JsonFormat annotation to your POJO.

public class TestPojo {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    public Date testDate;
}

2. Jackson properties

If you want to set Date serialization format globally - you have to tune Jackson configuration properties. E.g. for application.properties file format.

First one disables WRITE_DATES_AS_TIMESTAMPS serialization feature:

spring.jackson.serialization.write-dates-as-timestamps=false

Second one defines date format:

spring.jackson.date-format=dd-MM-yyyy

Or, for application.yml file format:

spring:
  jackson:
    date-format: "dd-MM-yyyy"
    serialization:
      write_dates_as_timestamps: false

3. Custom Serializer

If you want to take full control over serialization - you have to implement a custom StdSerializer.

public class CustomDateSerializer extends StdSerializer<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

    public CustomDateSerializer() {
        this(null);
    }

    public CustomDateSerializer(Class t) {
        super(t);
    }

    @Override
    public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) 
        throws IOException, JsonProcessingException {

        generator.writeString(formatter.format(date));
    }
}

And then use it with @JsonSerialize:

public class TestPojo {

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date testDate;
}
Share:
12,253
Akshay Lokur
Author by

Akshay Lokur

Loves Computers &amp; programming!👨🏻‍💻

Updated on June 04, 2022

Comments

  • Akshay Lokur
    Akshay Lokur almost 2 years

    I have to convert my POJO to JSON string in order to send to client code.

    When I do this however, java.util.Date field (having value "2107-06-05 00:00:00.0") from within my POJO gets translated as "1496592000000" which I think is a time since epoch. I want it to be something more readable in Json may be in 'DD/MM/YYYY' format.

    I am using RestEasy controller in Spring Boot application which handles the conversion for the Java object to JSON.

    Any clues what is going wrong?

    • P3trur0
      P3trur0 over 6 years
      Did you consider to use a date formatter, for example a SimpleDateFormat?
    • ΦXocę 웃 Пepeúpa ツ
      ΦXocę 웃 Пepeúpa ツ over 6 years
      post the code....
    • Akshay Lokur
      Akshay Lokur over 6 years
      But I am not doing any manual Json conversion. It's handled by RestEasy directly. If I get you right, do I need to add one more String field in my POJO with formatted date? But, this sounds like bad idea...
    • keuleJ
      keuleJ over 6 years
      That might be a duplicate to stackoverflow.com/questions/19229341/…
    • OneCricketeer
      OneCricketeer over 6 years
      RestEasy doesn't control the JSON mapping. You have some other library like Jackson doing that.
    • varren
      varren over 6 years
      @AkshayLokur i think you can annotate your POJO field with @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") or setup your jackson objectmapper with mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMP‌​S); if you want it to work globally
    • Andy Turner
      Andy Turner over 6 years
      Note that the two formats are different things: the timestamp is an instant, i.e. a single point on the timeline. The DD/mm/yyyy is a local date, i.e. a 24-hour (usually) long period of time, which can only be related to timestamps given a particular timezone. Your application may require one or the other, but don't think they are equivalent.
    • Sirga
      Sirga over 6 years
      Seconds since epoch is usually the best option, since it is easy to calculate with and avoids problems with the date encoding. The consumer of your service should translate it into the correct representation.
    • Andy Turner
      Andy Turner over 6 years
      @jan.vdbergh it entirely depends on what you are trying to represent: if you are representing the time something happened, e.g. a log event, timestamp is correct. If you are trying to represent a human-entered date, e.g. a birthday, a timestamp is not correct: your birthday doesn't change because you've traveled to a different time zone.
    • Akshay Lokur
      Akshay Lokur over 6 years
      @varren: Thanks, @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") works!