Spring Rest Controller handling Dates
Handling Date Request Parameters
Use Spring’s org.springframework.format.annotation.DateTimeFormat to specify the date format for the request parameter.
1 2 3 4 5 6 7 8 9
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) { return "Date: " + date; } }
|
use iso attribut to specify the date format for the request parameter.
1 2 3 4 5 6 7 8 9
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) { return "Date: " + date; } }
|
Handling DateTime Request Parameters
Use Spring’s org.springframework.format.annotation.DateTimeFormat to specify the date format for the request parameter.
1 2 3 4 5 6 7 8 9 10
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime dateTime) { return "Date: " + dateTime; } }
|
For LocalDateTime
1 2 3 4 5 6 7 8 9
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateTime) { return "Date: " + dateTime; } }
|
Handling Time Request Parameters
Use Spring’s org.springframework.format.annotation.DateTimeFormat to specify the date format for the request parameter.
1 2 3 4 5 6 7 8 9
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("time") @DateTimeFormat(pattern = "HH:mm:ss") LocalTime time) { return "Time: " + time; } }
|
Epoch time in Request parameters
You can also pass time in epoch time format and convert it to ZonedDateTime.
1 2 3 4 5 6 7 8 9 10 11 12
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("time") long time) { ZonedDateTime zonedDateTime = Instant.ofEpochSecond(time) .atZone(ZoneId.of("America/New_York")); return "Date: " + zonedDateTime; } }
|
You can also pass time in epoch millisecond format and convert it to ZonedDateTime.
1 2 3 4 5 6 7 8 9 10 11 12
| @RestController public class MyController {
@GetMapping("/api/data") public String getData(@RequestParam("time") long time) { ZonedDateTime zonedDateTime = Instant.ofEpochMilli(time) .atZone(ZoneId.of("America/New_York")); return "Date: " + zonedDateTime; } }
|