'Spring Boot REST API returns date in milliseconds

In my project setup, I've created sample API's and returns current date. But it returns milliseconds. What is the problem in serialise java object to json.? Here I've attached screen shots for your reference.

enter image description hereenter image description here

code:`@GetMapping("/refresh/core/cache/demo") 
public Date getDate(){
 log.info("Current date is : {}",new Date());
 return new Date(); 
}

In my attachments, log prints correct date format but it returns in millisecond. why it did not return date as a date format.?



Solution 1:[1]

 Json supports only few data types. Those are Number, String, Boolean, 
 Array, Object and null. We need to send the in these formats only.

 We need to format the date and return the String as response.
 We need to Convert the date from  Date to String.

 @GetMapping("/refresh/core/cache/demo") 
 public String getDate(){
 log.info("Current date is : {}",new Date());
 Date date = new Date();  
 SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");  
 retutn formatter.format(date); 
 }

Solution 2:[2]

There are different solutions.

  • Add a dependency on com.fasterxml.jackson.datatype:jackson-datatype-joda.I think you may already have this dependency. Configure Jackson not to format dates as timestamps by adding spring.jackson.serialization.write-dates-as-timestamps: false to your application.properties file.

  • Annotate the Date field or getter method with @JsonFormat(pattern="yyyy-MM-dd")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajasekhar
Solution 2 Faramarz Afzali