传递日期以在 Spring MVC 中请求参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14766818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:42:55  来源:igfitidea点击:

Passing date to request param in Spring MVC

springspring-mvc

提问by user1755645

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

我是 Spring MVC 的新手 - 我试图将我的 javascript 中的日期作为请求参数传递

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

我的问题是如何从 javascript 进行调用 - 就像 URL 应该是什么样子一样

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

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

我是否需要一种解析日期的方法,以便 Spring 可以识别它?

回答by Sudhakar

Use @DateTimeFormat("MMddyyyy")

@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) {

回答by dannrob

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

这现在也是@DateTimeFormat,它支持一些常见的 ISO 格式

回答by Kimchi Man

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

使用 @DateTimeFormat(pattern="yyyy-MM-dd") 其中 yyyy 是年,MM 是月,dd 是日期

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