Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format in the json output using spring boot

I am working on spring boot for creating a REST application. And I have a DTO as shown below:

public class Subject {  private String uid; private String number; private String initials; private Date dateOfBirth; 

And I use Spring-Hateos and the reurn type of my controller is ResponseEntity<Resources<Resource<Subject>>>. I need the date to be displayed in the "yyyy-mm-dd" format.

like image 666
Pramod Avatar asked Mar 13 '15 08:03

Pramod


People also ask

How do you specify date format in Spring boot?

If your date is argument to a function, you can use @DateTimeFormat(pattern = "yyyy-MM-dd") to define a pattern (ie. org. springframework. format.

How do you format a date in JSON?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.

What is @JsonFormat in Spring boot?

@JsonFormat is a Jackson annotation that we use to specify how to format fields and/or properties for JSON output. Specifically, this annotation allows us to specify how to format Date and Calendar values according to a SimpleDateFormat format.

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.


1 Answers

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {       private String uid;      private String number;      private String initials;       @JsonFormat(pattern="yyyy-MM-dd")      private Date dateOfBirth;         //Other Code    }   

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

like image 63
Yagnesh Agola Avatar answered Oct 09 '22 22:10

Yagnesh Agola