【问题标题】:Parsing html datetime-local type input into java LocalDateTime将html datetime-local类型输入解析为java LocalDateTime
【发布时间】:2017-04-01 06:06:38
【问题描述】:

代码

JSP:

<div class="col-md-4 col-sm-6 col-xs-12">
    <fmt:formatDate value="${sighting.sightingDateAsDate}" var="sightingDateString" pattern="yyyy-MM-dd'T'hh:mm:ss"/>
    <sf:input type="datetime-local" class="add-form form-control" path="sightingDate" value="${sightingDateString}"/>
</div>

Controller:

String sightingDateString = request.getParameter("sightingDate");
LocalDateTime sightingDate = LocalDateTime.parse(sightingDateString.replace("T"," "), DateTimeFormatter.ISO_DATE_TIME);

我正在处理这个编辑表单。 fmt:formatDate 是将SightingDate 转换为html 可读的格式,以便输入字段datetime-local 将填充现有的LocalDateTime 值。

现在的问题是将其转换回 LocalDateTime。 我得到的当前错误是:

错误

Request processing failed; nested exception is 
java.time.format.DateTimeParseException: Text '2017-03-22 01:00' could not be parsed at index 10

我也试过不使用替换(“T”,“”)。错误将显示 Text '2017-03-22T01:00' 而不是 Text '2017-03-22 01:00'

【问题讨论】:

  • ISO_DATE_TIME 格式中有 T,所以在我看来,你用空格替换 T 是在破坏事情。
  • 使用LocalDateTime.parse(sightingDateString, DateTimeFormatter.ISO_DATE_TIME); 解析2017-03-22T01:00 没有问题。我想你的问题在其他地方。 Minimal, Complete, and Verifiable example,好吗?
  • 在你的 JSP 中,pattern="yyyy-MM-dd'T'hh:mm:ss",应该是大写的Hs (HH:mm:ss)?

标签: java jsp datetime


【解决方案1】:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm");
Date date = (Date)formatter.parse(sightingDateString); 

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2017-04-12
    • 1970-01-01
    • 2020-12-23
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多