DateTime parsing issue using @DateTimeFormat

Viewed 355

I am getting issue while working with @DateTimeFormat in my SpringBootApplication. Below is the code snippet where I am getting the issue`

package com.example.demo;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
public class DateTimeController {

    @GetMapping("/test/datetime/{id}")
    public String testDateParsing(@PathVariable String id,
                                  @RequestParam("since") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssz") LocalDateTime since) {

        System.out.println("id : " + id);
        System.out.println("since : " + since);

        return "success";
    }
}

The Code is working fine with datetime of EST time zone -

http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43-05:00 
- I am getting SUCCESS response for 2021-03-02T10:57:43-05:00 (EST Time)

The Code is Not Working with datetime of IST time zone -

http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43+05:30 
- I am getting ERROR response for 2021-03-02T10:57:43+05:30 (IST Time)

Exception - "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; 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.LocalDateTime] for value '2021-03-02T10:57:43 05:30'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2021-03-02T10:57:43 05:30]"

Any idea how to fix this issue?

2 Answers

The problem is the + sign in your request URL. This is a reserved sign.

You must URL encode the query parameters. And this will then look like this:

GET http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43%2B05:30

The plus sign ("+") in your URL is being automatically converted to a space character (" "). This can be fixed by URL encoding the space character as "%2B".

http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43%2B05:30

This issue can be confirmed by a close read of the exception message, which is showing the parsed text as having a space in it, not the plus sign:

Parse attempt failed for value [2021-03-02T10:57:43 05:30]"

This conversion of the plus sign to a space is a fairly common conversion in URLs, and it appears that Spring is doing this by default.

Related