Denis Stephanov
Denis Stephanov

Reputation: 5241

Deserialize LocalDateTime from incoming JSON

I have created Spring Boot REST Api and I need handle with REST Controller object which contains LocalDateTime and LocalDate variables.

here is my sample object:

public class Foo {
   private LocalDateTime dateTime;
   private LocalDate date;

   // others variables, geeters and setters
}

and my controller:

@PostMapping("/foo")
public void fooApi(@RequestBody @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Foo foo) {
    // calling some service
}

I've tried solution above, and send that json:

{  
   "dateTime":"2018-02-05T11:59:11.332Z",
   "date":"2018-02-05T11:59:11.332Z"
   ...
}

enter image description here

As you can see I sending time 12:59 .. but controller hit with time 11:59. Can you tell me how correct pass date and time to spring rest? I also have this in application.properties:

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

Thanks in advice.

Upvotes: 2

Views: 18053

Answers (2)

holmis83
holmis83

Reputation: 16604

LocalDateTime does not hold any time-zone information. Assuming that you want time without timezone (local time) and receive the time for the client/user, you should send without timezone:

{  
  "dateTime":"2018-02-05T12:59:11.332",
   ...
}

Note from your example, time part is changed to 12:59, and Z for UTC timezone is removed.

Upvotes: 3

Priya Jain
Priya Jain

Reputation: 830

Please correct the description as in json you are passing 11:59 but you are saying you are passing 12:59.

As per the difference that you have mentioned, It is because of timezone.

d.toISOString is giving the date in UTC format. However, d= new Date() is giving the timezone(system timezone) specific date, in your case it is CET(Central European Time) which is utc+01:00 means 1 hour ahead of utc time.

Upvotes: 0

Related Questions