Tobia
Tobia

Reputation: 9506

Spring MVC REST Date input and timezones

I'm working with Spring MVC and I have a custom date/datetime parser:

@Bean
public FormattingConversionService mvcConversionService() {
    DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);

    DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
    dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    dateTimeRegistrar.registerFormatters(conversionService);

    DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
    dateRegistrar.setFormatter(new DateFormatter("yyyy-MM-dd"));
    dateRegistrar.registerFormatters(conversionService);

    return conversionService;

}

I have some trouble with timezone and @PathVariable or @RequestBody inputs.

@GetMapping("/report/{date}")
public void testPath(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date){
   ...
}

@PostMapping("/report")
public void testBody(@RequestBody Date filter){
    ...
}

Calling this URL http://localhost/report/2022-06-01 the first controller parses the date to 2022-06-01 00.00 CEST

Calling this URL http://localhost/report with this body "2022-06-01" the second controller parses the date to 2022-06-01 +02.00 CEST (adjusting the time adding +2h).

Is there any way to force the FormattingConversionService to consider the date to local timezone?

Upvotes: 0

Views: 781

Answers (1)

Magdalena
Magdalena

Reputation: 21

I have the same problem. With JsonFormat you can get the same date if you set timezone to your local. Unfortunately, there is no way to set timezone dynamically.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Europe/Warsaw")
private Date date;

In my case, it only worked for POST RequestBody parameter. I couldn't change timezone of GET path parameter.

Upvotes: 1

Related Questions