Search code examples
javaspring-bootcontrollerzoneddatetime

Spring rest controller removes plus sign from zonedatetime in query parameter


I have UT, that succesfully passed

    @Test
    public void test() {
        String text1 = "2009-07-10T14:30:01.001Z";
        String text2 = "2009-07-10T14:30:01.001+03:00";
        DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");

        ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(text1, f);
        ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(text2, f);

        System.out.println(zonedDateTime1);
        System.out.println(zonedDateTime2);
    }

The output is

2009-07-10T14:30:01.001Z
2009-07-10T14:30:01.001+03:00

But, when I try to use this pattern on spring-controller

    @GetMapping
    public ResponseEntity get( @RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
                                               ZonedDateTime start) {
        Dto result = service.get(start);
        return new ResponseEntity(result, getHeaders(), HttpStatus.OK);
    }

It works only when I pass Z instead timezone, for example

2009-07-10T14:30:01.001Z

But when try to pass timezone offset - there is error message

"Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.ZonedDateTime] for value '2009-07-10T14:30:01.001 03:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2009-07-10T14:30:01.001 03:00]",

I try to pass request by postman like this

POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001+03:00
header: Content-Type application/json

Solution

  • You have to encode the url when you have special characters like plus sign (+)

    POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001%2B03:00