Embracing the Messiness in Search of Epic Solutions

Spring MVC: Failed to convert value of type ‘java.lang.String’ to required type ‘java.time.LocalDateTime’

Posted

in

PROBLEM

Given the following controller …

@RestController
@RequestMapping(value = '/controller')
class MyController {

    @RequestMapping(method = RequestMethod.GET)
    ResponseEntity main(@RequestParam(name = 'dateTime') LocalDateTime dateTime) {
        // ...

        return ResponseEntity.noContent().build()
    }
}

When executing …

GET https://localhost:8443/controller?dateTime=2017-06-22T17:38

… the web service call returns 400 Bad Request with the following error in the console log:-

Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
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 java.time.LocalDateTime] for value '2017-06-22T17:38';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-06-22T17:38]

SOLUTION

One solution is to change the data type from java.time.LocalDateTime to java.lang.String before parsing it to java.time.LocalDateTime. However, it is a little more verbose than I like.

A better way is to leverage @DateTimeFormat:-

@RestController
@RequestMapping(value = '/controller')
class MyController {

    @RequestMapping(method = RequestMethod.GET)
    ResponseEntity main(@RequestParam(name = 'dateTime') @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") LocalDateTime dateTime) {
        // ...

        return ResponseEntity.noContent().build()
    }
}

Tags:

Comments

3 responses to “Spring MVC: Failed to convert value of type ‘java.lang.String’ to required type ‘java.time.LocalDateTime’”

  1. vinay Avatar
    vinay

    Simillary iam facing
    “Failed to convert value of type [java.lang.String] to required type [int]; nested exception is java.lang.NumberFormatException: For input string: ‘updateTable’ “. pls help me guyz

  2. Matt Weiler (@MattWeiler) Avatar

    This works well for date patterns that don’t have timestamp, but if your pattern includes a timestamp, it will fail to parse a String formatted correctly with timestamp.

  3. Mark Broadhead Avatar
    Mark Broadhead

    Just wanted to say thank you and this solved my issue with Date serialization. Thank you for the effort in making this post.

Leave a Reply to vinayCancel reply