How to accept Date params in a GET request to Spring MVC Controller?

how to pass date from jsp to controller in spring mvc
spring requestparam date format
spring mvc date input example
spring boot datetimeformat
spring.jackson.date-format timestamp
spring boot date format
spring boot date validation
spring.jackson.date-format not working

I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows:

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) {
        //Content goes here
    }

The request is sent correctly as I'm checking with Firebug. I get the error:

HTTP Status 400: The request sent by the client was syntactically incorrect.

How can I make the controller accept this format of Date? Please help. What am I doing wrong?

Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
        //Content goes here
    }

Yes, it's simple. Just add the DateTimeFormat annotation.

Working with Date Parameters in Spring, The problem is that Spring cannot convert a request parameter string into DATE. The controller class that uses this date format looks as follows: We can apply the @DateTimeFormat annotation to java.util. P.S. You can get the example application of this blog post from Take a look at this blog post. Questions: I’ve a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows: @RequestMapping(value="/fetch" , method=RequestMethod.GET) public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) { //Content goes here } The request is sent correctly as I’m checking with Firebug.

This is what I did to get formatted date from front end

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
  @ResponseBody
  public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
   return OK;
  }

You can use it to get what you want.

Parsing Date and Time Information From a Request Parameter, Passing a Date parameter in a Spring MVC controller is easy. The DateTimeFormat annotation lets you define the format of the date and does� I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows: @RequestMapping(value="/fetch" , method=RequestMethod.GET) public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) { //Content goes here } The request is sent correctly as I'm checking with Firebug.

... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:

spring.mvc.date-format=yyyy-MM-dd

Date Parameter in Spring MVC Controller, The spring.mvc.date-pattern property only applies to parameters of type java.util. The controller advice gets applied to all controller instances. And if we try it out, if works for GET requests without date query parameter. Accept, OnOff. Name, Facebook. Provider, Facebook. Purpose, Used to unlock� In this period I am studing the Spring MVC showcase example (downloadable from STS dasboard) and I have some simple question about the Request Mapping examples:. 1) In my home.jsp page I have this link:

Below solution perfectly works for spring boot application.

Controller:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return userRepository.getAllInactiveUsers(dateTime);
}

So in the caller (in my case its a web flux), we need to pass date time in this("yyyy-MM-dd HH:mm:ss") format.

Caller Side:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
    Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
            .uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
            .bodyToFlux(User.class).map(UserDto::of);
    return userDto;
}

Repository:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);

Cheers!!

Parsing of LocalDate query parameters in Spring Boot, date information from a request parameter by using Spring MVC and Get the example Duration: 4:58 Posted: Feb 28, 2016 @AdamGent The question was asked at a time when Spring 3.2 was not yet released. Go back and take a look at the JavaDoc for 3.1, and you will notice there is no such mention of utilizing @RequestParam on a Map<String,String> to retrieve all query string parameters.

If you want to use a PathVariable, you can use an example method below (all methods are and do the same):

//You can consume the path .../users/added-since1/2019-04-25
@GetMapping("/users/added-since1/{since}")
public String userAddedSince1(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

//You can consume the path .../users/added-since2/2019-04-25
@RequestMapping("/users/added-since2/{since}")
public String userAddedSince2(@PathVariable("since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date since) {
    return "Date: " + since.toString(); //The output is "Date: Wed Apr 24 19:00:00 COT 2019"
}

//You can consume the path .../users/added-since3/2019-04-25
@RequestMapping("/users/added-since3/{since}")
public String userAddedSince3(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

Parsing Date Information From a Request Parameter, Controller @RequestMapping("employees") public class addAttribute(" employee request by id and paystub dates : " + employeeId + ", " + startDate + ", " + http://localhost:8080/spring-mvc-query-param/employees?dept=IT Previously, I was taking the date as String and then processing it using the joda formatter mentioned above in the service layer, but now I want to add request validation in the controller, which means that if the request is syntactically incorrect, the request shouldn't even go to the service layer.

Spring MVC - Binding URL query parameters with , In this particular example the method has no parameters and returns a The get () method has a further @RequestMapping refinement: it only accepts GET with the @PathVariable annotation can be of any simple type such as int, long, Date. java.util.Locale for the current request locale, determined by the most specific� This means that if the parameter isn’t present in the request, we'll get an error: GET /api/foos HTTP/1.1 ----- 400 Bad Request Required String parameter 'id' is not present We can configure our @RequestParam to be optional, though, with the required attribute:

15.3 Implementing Controllers, The Spring Web model-view-controller (MVC) framework is designed around accepts GET requests, meaning that an HTTP GET for /appointments invokes A @PathVariable argument can be of any simple type such as int, long, Date, etc. The 'required' element of @RequestParam. This element defines whether the parameter is required. The default is true. That means the status code 400 will be returned if the parameter is missing in the request.

17. Web MVC framework - Project Metadata API Guide, This Spring MVC annotation shows that a method parameter should bound to Above request get the following response from the controller: Hello Let's take a simple use case when we like to store the email address in the Id field. application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun� In this short tutorial, we'll take a look at how to accept Date, LocalDate and LocalDateTime parameters in Spring REST requests, both at the request and application levels. 2. The Problem

Comments
  • I was going to write an answer but you beat me. You can also use @DateTimeFormat(iso=ISO.DATE), which is the same format. BTW, if you can I suggest that you use the Joda DateTime library. Spring supports it really well.
  • The answer is generally ok, BUT! Is there a way to configure it as a default to Spring? It's a little bit overkill to put @DateTimeFormat in every controller you have...
  • @Luciano of course you can do @DateTimeFormat(iso = ISO.DATE_TIME) as well
  • @thorinkor In Spring Boot you can set the spring.mvc.date-format attribute in application.properties or add beans that implement the org.springframework.format interface (extending org.springframework.format.datetime.DateFormatter is probably the way to go). In non-Boot Spring you can @Override the addFormatters method of WebMvcConfigurerAdapter and add your Formatter-implementing beans there.
  • Didn't get it. What's the point of adding @​DateTimeFormat to @​PathVariable if you receive dateString as String, not as Date?