如何读取输入类型=“日期”到java对象日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18378612/
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
How to read input type="date" to java object Date?
提问by
I have so input
我有这么输入
<input type="date" name="date">
How to read from this input to java object of class java.util.Date?
如何从此输入读取到类 java.util.Date 的 java 对象?
P.S. Date date is a field of my Bean, which I read so:
PS 日期日期是我 Bean 的一个字段,我是这样读的:
@RequestMapping("/updateVacancy")
public String updateVacancy(@ModelAttribute("vacancy") Vacancy vacancy){
vacancyService.update(vacancy);
return "VacancyDetails";
}
回答by JB Nizet
The specificationsays:
规范说:
value = date
A string representing a date. A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.
Example:
1996-12-19
价值 = 日期
表示日期的字符串。[RFC 3339] 中定义的有效完整日期,附加条件是年份部分是四位或更多位数字,表示大于 0 的数字。
例子:
1996-12-19
So you'll have to parse the parameter value according to this format. At server-side, you'll get the parameter value exactly as if the field was an input of type text, and its value was a date formatted using the yyyy-MM-dd
pattern.
所以你必须根据这种格式解析参数值。在服务器端,您将获得参数值,就像该字段是文本类型的输入一样,其值是使用该yyyy-MM-dd
模式格式化的日期。
回答by qiGuar
You may receive date as text and then parse it to java.util.Date
您可能会以文本形式接收日期,然后将其解析为 java.util.Date
For example like this
例如像这样
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parsed = format.parse(date);
You should also check that received value corresponds to you desired format.
您还应该检查接收到的值是否符合您所需的格式。
回答by Salvioner
As suggested hereyou should declare an @InitBinder in your controllerthat handles the parsing of Date objects from Strings:
正如这里所建议的,你应该在你的控制器中声明一个 @InitBinder来处理来自字符串的 Date 对象的解析:
/* put this in your Controller */
@InitBinder
private void dateBinder(WebDataBinder binder) {
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);
}