Date Parameter in Spring MVC Controller

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.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *