Passing date to request param in Spring MVC

SpringSpring Mvc

Spring Problem Overview


I am new to Spring MVC - and I am trying to pass a date from my javascript as a request Param

My controller looks something like -

public @ResponseBody List<RecordDisplay> getRecords(
			@RequestParam(value="userID") Long userID,
			@RequestParam(value="fromDate") Date fromDate,
			@RequestParam(value="toDate") Date toDate) {

The question I have is how do I make the call from javascript - as in what should the URL look like

for eg. - /getRecords?userID=1&fromDate=06022013&toDate=08022013'

Do I need a way to parse the date so Spring can recognize it?

Spring Solutions


Solution 1 - Spring

Use @DateTimeFormat("MMddyyyy")

public @ResponseBody List<RecordDisplay> getRecords(
@RequestParam(value="userID")  Long userID,
@RequestParam(value="fromDate")     @DateTimeFormat(pattern="MMddyyyy") Date fromDate,
@RequestParam(value="toDate")     @DateTimeFormat(pattern="MMddyyyy") Date toDate) {

Solution 2 - Spring

This is now @DateTimeFormat as well which supports some common ISO formats

Solution 3 - Spring

Use @DateTimeFormat(pattern="yyyy-MM-dd") where yyyy is year, MM is month and dd is date

public @ResponseBody List<Student> loadStudents(@DateTimeFormat(pattern="yyyy-MM-dd") Date birthDay) {
    ...
}

Solution 4 - Spring

You should use your application.properties (or any other project properties) and set the environment variable spring.mvc.format.date.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1755645View Question on Stackoverflow
Solution 1 - SpringSudhakarView Answer on Stackoverflow
Solution 2 - SpringdannrobView Answer on Stackoverflow
Solution 3 - SpringKimchi ManView Answer on Stackoverflow
Solution 4 - SpringnotforwardView Answer on Stackoverflow