0

I'm trying to write a controller request method that accepts a date parameter that is sent as an iso formatted date time string. It looks like you can specify a format manually, annotating the method parameter with @DateTimeFormat(pattern="yyyy-MM-dd") but I want to use the iso setting. I.e. @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME). Using the ISO Date Time format I can't even get it to parse the example date in the documentation. I'm wondering if I'm doing something wrong.

Here is my controller class:

@RestController
public class DateController {

    @RequestMapping(path = "/echoIsoDate", method = RequestMethod.GET)
    public ResponseEntity<String> echoIsoDate(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date date){
        return new ResponseEntity<>(date.toString(), HttpStatus.OK);
    }

    @RequestMapping(path = "/echoDumbDate", method = RequestMethod.GET)
    public ResponseEntity<String> echoDumbDate(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date){
        return new ResponseEntity<>(date.toString(), HttpStatus.OK);
    }
}

When I try to call this controller with the date I actually want to parse it doesn't work:

http://localhost:8080/echoIsoDate?date=2015-12-30T00:00:00.000Z

When I try to call this controller with the example date from the documentation it doesn't work:

http://localhost:8080/echoIsoDate?date=2000-10-31%2001:30:00.000-05:00

The second controller method does work. e.g calling http://localhost:8080/echoDumbDate?date=1970-01-01 returns Thu Jan 01 00:00:00 CST 1970 (But then it's in CST, which presumably is in my system timezone).

Questions:

  • What am I doing wrong in echoIsoDate()? Or is there a bug in Spring?
  • For echoDumbDate() is there a way to specify the timezone I want, so that it will always use UTC?
Community
  • 1
  • 1
David
  • 14,569
  • 34
  • 78
  • 107

1 Answers1

1

try this instead

@RequestMapping(path = "/echoIsoDate", method = RequestMethod.GET)
public ResponseEntity<String> echoIsoDate(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date date){
    return new ResponseEntity<>(date.toString(), HttpStatus.OK);
}
tashi
  • 782
  • 6
  • 5