pioto
pioto

Reputation: 2582

Why is Spring parsing my date wrong?

I have a simple Spring MVC controller, with a method that takes a java.util.Date object as a parameter:

@Controller
public class ExampleController {

    @RequestMapping(value = "/foo", params = { "foo", "date" }, produces = "application/json")
    @ResponseBody
    public Blah getFoo(@RequestParam String foo, @RequestParam @DateTimeFormat(iso = ISO.DATE_TIME) Date date) {
        // do something interesting here
    }
}

If I feed this a date parameter generated by Moment.js, for example 2015-12-17T12:04:10-05:00, it seems to act as though I gave it a 12 hour time, because the Date I get out the other end returns this from it's .toString(): Thu Dec 17 00:04:00 EST 2015. For comparison, if I feed it a time string like 2015-12-17T09:04:10-05:00, I get the expected Thu Dec 17 09:04:00 EST 2015, and 2015-12-17T13:04:10-05:00 yields Thu Dec 17 13:04:00 EST 2015.

I've tried various tweaks to the above, such as omitting the @DateTimeFormat completely, or using pattern = "yyyy-MM-dd'T'HH:mm:ssZ", but I always seem to get the same result.

Is this a possible bug in Spring? Or, is there some bit of configuration I may be missing?

I'm using Spring Boot 1.3.0.

Upvotes: 1

Views: 2361

Answers (1)

pioto
pioto

Reputation: 2582

It seems that a globally registered formatter was involved, and it overrode the @DateTimeFormat annotation I had in place. And, that formatter was using the pattern "yyyy-MM-dd'T'hh:mm, which is why I was seeing the ambiguity with parsing around noon...

Removing that formatter from my WebMvcConfigurerAdapter#addFormatters(FormatterRegistry registry) method seemed to be enough to allow the @DateTimeFormat to kick in. I also found I had to use the pattern above, rather than the iso = ISO.DATE_TIME flavor, because my data didn't have the fractional seconds included.

Upvotes: 2

Related Questions