【问题标题】:How to read input type="date" to java object Date?如何将输入类型 =“日期”读取到 java 对象日期?
【发布时间】:2013-08-25 01:48:49
【问题描述】:

我有意见

 <input type="date"  name="date">

如何从这个输入中读取 java.util.Date 类的 java 对象?

附:日期日期是我的 Bean 的一个字段,我是这样读的:

@RequestMapping("/updateVacancy")
    public String updateVacancy(@ModelAttribute("vacancy") Vacancy vacancy){
        vacancyService.update(vacancy);
        return "VacancyDetails";
    }

【问题讨论】:

标签: java html spring


【解决方案1】:

您可以接收文本形式的日期,然后将其解析为 java.util.Date

比如这样

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parsed = format.parse(date);

您还应该检查收到的值是否与您想要的格式相对应。

【讨论】:

  • Time 有什么类似的吗?
【解决方案2】:

The specification 说:

值 = 日期

表示日期的字符串。 [RFC 3339] 中定义的有效完整日期,附加条件是年份部分是四位或更多位,表示大于 0 的数字。

例子:

1996-12-19

所以你必须根据这种格式解析参数值。在服务器端,您将获得参数值,就像该字段是文本类型的输入一样,其值是使用yyyy-MM-dd 模式格式化的日期。

【讨论】:

    【解决方案3】:

    按照here 的建议,您应该在您的控制器 中声明一个@InitBinder,以处理从字符串中解析日期对象:

    /* 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);
    }
    

    【讨论】:

      【解决方案4】:

      什么对我有用:

      1. 在DTO对象中,与HTML链接的变量被声明为String;
      2. 当转移到最终的对象时,简单的解析工作:
      LocalDate localDateInFinalObject = LocalDate.parse(DateAsStringFromDTOObject)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-26
        • 2014-07-21
        • 2021-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        • 2017-04-25
        相关资源
        最近更新 更多