Trant
Trant

Reputation: 3609

How do I get DateTimeFormat working with Spring MVC?

I have a controller method that looks like this:

@RequestMapping(headers = "Accept=application/json;charset=utf-8", value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public Blah test(@ModelAttribute MyObject parms, HttpServletRequest request) throws Exception { 

        // blah blah
    }

MyOBject looks like this:

public class MyObject{

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    private Calendar someDate;
    // blah blah setters getters

When I call this method via browser like so:

http://localhost:8080/blah/test?someDate=2011-07-11T21%3A28%3A59.564%2B01%3A00

I am getting Error 400 - Bad Request.

I kept trying with various different values for someDate (always using a URL encoder to encode the special chars) and nothing works. All the ones I tried (pre-URL encoding):

2000-10-31 01:30:00.000-05:00

2011-07-11T21:28:59.564+01:00

2014-04-23T13:49:28.600Z

I know dates dont match I am merely trying to get Spring to parse this damn date for me into that Calendar object!! (Though really I would prefer it was a java.sql.Timestamp but that's probably even harder to get done)

How do I do this?

Am I writing the date wrong? Am I using the wrong annotation for properties in a ModelAttribute (Note I have many other parameters so I bundle them up in a ModelAttribute object, dont want to use @RequestParm)

The error that shows up in log file:

Field error in object 'myObject' on field 'someDate': rejected value [2011-07-11T21:28:59.564+01:00]; codes [typeMismatch.myObject.someDate,typeMismatch.someDate,typeMismatch.java.util.Calendar,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [myObject.someDate,someDate]; arguments []; default message [someDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Calendar' for property 'someDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Calendar for value '2011-07-11T21:28:59.564+01:00'; nested exception is java.lang.IllegalArgumentException: Unable to parse '2011-07-11T21:28:59.564+01:00']

Upvotes: 5

Views: 12180

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

This

'2011-07-11T21:28:59.564+01:00'

value is incorrect since the expected format is

yyyy-MM-dd'T'HH:mm:ss.SSSZ

you can't have a : inside the +0100 timezone offset.

You must be url encoding it wrong.

Upvotes: 9

Related Questions