I receive a JSON in string format which I'm converting to Java Object Class using the Gson library. In that JSON the DateTime field is annotated with @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") The original format in which the date is "creationDate": "2022-10-25T10:38:32.000 01:00" after converting the JSON to Java Object Class the format of the DateTime fields changes to Tue Oct 25 15:08:32 IST 2022 rather than converting it to the required format. Below is an example of my POJO class
@Data
public class Root{
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date creationDate;}
Below is an example of how I'm converting my string to Java Object Class
String fileContent = Files.readString(Path.of"**Path of the file**"));
Root root = new Gson().fromJson(fileContent, Root.class);
JSON example:
root{
"creationDate":"2022-10-25T10:38:32.000 01:00"
}
I dont understand why this is happening. I know I can convert it using new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sDate1) But I want to understand why @annotation is not working
CodePudding user response:
You can try this Jackson annotation over the date field to format date :-
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSSX")
CodePudding user response:
Date
(old obsolete style), LocalDateTime
, ZonedDateTime
do not possess an inherent format.
Date's toString() as used in System.out.println(new Date());
gives that format you saw.
"2022-10-25T10:38:32.000 01:00" is the ISO standard format, T
signifying the start of the time part. It is the format of an OffsetDateTime
which is still Locale (country) independent, and does not deal with daylight savings time. ZonedDateTime
would be better.
OffsetDateTime t = OffsetDateTime.parse("2022-10-25T10:38:32.000 01:00");
ZonedDateTime zt = t.toZonedDateTime(); // Default zone
Date d = Date.fromInstant(t.toInstant());
For other format variants you can use a DateTimeFormatter
.