Date Parameter in Spring MVC Controller

Published on March 1, 2015 by

Need to pass a date as a java.util.Date instance in a Spring MVC controller action? Then you have come to the right place. You might have tried the below approach and encountered a good old 404 Not Found error.

@Controller
public class CompanyController {
    @RequestMapping("/company/added-since/{since}")
    public String showAddedSince(@PathVariable("since") Date since) {
        return "companies-added-since";
    }
}

What you have to do instead is to use the @DateTimeFormat annotation before your Date argument and define the format of the date, like this:

@Controller
public class CompanyController {
    @RequestMapping("/company/added-since/{since}")
    public String showAddedSince(@PathVariable("since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date since) {
        return "companies-added-since";
    }
}

The @DateTimeFormat annotation lets you specify the format with the ISO enum. Please click the link to see the available options, or let your IDE’s IntelliSense guide you. The format specified above is yyyy-MM-dd, e.g. 2015-03-01. Alternatively, the format can be specified with the pattern attribute of the annotation. The below is equivalent to the example above.

@Controller
public class CompanyController {
    @RequestMapping("/company/added-since/{since}")
    public String showAddedSince(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
        return "admin-companies-added-since";
    }
}

The annotation also supports more complex use cases such as including time. Please note that the annotation can be used in other contexts than with a method argument as well; this article merely gives an example of a use case in which the @DateTimeFormat annotation can be used within a Spring MVC controller.

Featured

Learn Spring Framework today!

Take an online course and become a Spring Framework champion!

Here is what is covered:

  • The Spring Framework basics, including Spring MVC
  • How to work with JDBC and MySQL (in the context of Spring)
  • Build real applications step by step
  • A detailed walkthrough of Spring's core concepts
  • ... and much more!
Spring Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.