Date Binding in Spring MVC

  • Post author:
  • Post category:Java

Here’s how to accept java.util.Date parameters in your Spring MVC Controller. This has been tested on Spring 3.1.

1. In your Spring MVC Controller, add a request parameter with a DateTimeFormat annotation. Something like:

public String foo(@RequestParam @DateTimeFormat(pattern="MM/dd/yyyy") Date date) {
    System.out.println(date);
    return "foo"
}

2. Add Joda-Time to your web application. If you’re using Maven, you can add the following dependency to your pom.xml.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.2</version>
</dependency>

3. In your web page, pass the date to the server in the format MM/dd/yyyy. We are using the jQuery UI Datepicker in our web application, so we have something like this:

$("#datepicker").datepicker({dateFormat: 'mm/dd/yy'});

Where #datepicker is the selector, which looks for a text input with the id=”datepicker”.

4. Submit the request with the date parameter in the format MM/dd/yyyy to your Spring MVC controller and you should see the date passed printed in the server console.

This Post Has 2 Comments

  1. Nathan

    Thank you, I applied this differently but it was still helpful!

  2. Khaula

    Awesome it helped

Comments are closed.