如何在mysql查询中插入日期?

时间:2017-04-28 00:15:18

标签: java java-time

我正在尝试在datetime类型('0000-00-00 00:00')的属性中保存日期和时间。我使用了以下代码。但是错误 - HTTP Status 500 - Internal Error出现了,因为line 6显示以下错误消息: java.time.format.DateTimeParseException: Text '2017-04-30 23:59 could not be parsed at index 10

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");
LocalDateTime forDate = LocalDateTime.parse(newDate, formatter);
out.println(forDate);
ps = con.prepareStatement("INSERT INTO reminder_logs VALUES(NULL, ?, ?)");
ps.setInt(1, r_id);                        
ps.setDate(2, forDate);
i = ps.executeUpdate();

已编辑:错误 - HTTP状态500 - 内部错误 HTTP Status 500 - Internal Error

我尝试使用setTimestamp(2, forDate)代替setDate(2, forDate),但后来收到错误消息:不兼容的类型:LocalDateTime无法转换为Timestamp。 我尝试从以下链接中获取参考资料,但没有一个帮助:

  1. java.time.format.DateTimeParseException: Text '2016-2-2' could not be parsed at index 5

  2. How to set current date and time using prepared statement?

  3. Unparseable date error on Java

  4. 我该怎么做才能解决这个错误? 我正在运行java se 8。

1 个答案:

答案 0 :(得分:2)

java.time.format.DateTimeParseException的原因是您在格式字符串中使用hh而不是HH

From the docs

H       hour-of-day (0-23)          number            0
h       clock-hour-of-am-pm (1-12)  number            12

然后您将提供24小时格式化的时间戳。

// runnable example

String newDate = "2017-04-30 23:59";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");
LocalDateTime forDate = LocalDateTime.parse(newDate, formatter);
System.out.println(forDate);

结果:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2017-04-30 23:59' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 23
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at _Scratchpad.SO.main(SO.java:12)
Caused by: java.time.DateTimeException: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 23
....

此追踪清楚地表明时间超出范围:

  

ClockHourOfAmPm的值无效(有效值1 - 12):23