我正在尝试转换存储在数据库(作为datetime)中的字符串值(最初是一个LocalDateTime变量),并将其解析为LocalDateTime变量。我尝试过使用格式化程序:
String dTP;
dTP=(rs.getString("arrivedate"));
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime dateTimeParked = LocalDateTime.parse(dTP,formatter);如果没有格式化程序:
String dTP;
dTP=(rs.getString("arrivedate"));
LocalDateTime dateTimeParked = LocalDateTime.parse(dTP);但我每次都会得到相同的错误:
Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '2016-07-09 01:30:00.0' could not be parsed at index 10我的想法是索引10是日期和时间之间的空格。
有人能帮我这个忙吗?我已经做了几个小时了:
发布于 2016-07-25 12:37:50
导致此问题的格式中存在错误。请参考https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.The日期时间格式为'2011-12-03T10:15:30‘。下面的内容会给你一些启发。
public static void main(String[] args) throws Exception {
String isoDate = "2016-07-09T01:30:00.0";
// ISO Local Date and Time '2011-12-03T10:15:30'
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime dateTimeParked = LocalDateTime.parse(isoDate, formatter);
System.out.println(dateTimeParked);
String date = "2016-07-09 01:30:00.0";
DateTimeFormatter formatterNew = DateTimeFormatter.ofPattern("yyyy-LL-dd HH:mm:ss.S");
LocalDateTime dateTimeParkedNew = LocalDateTime.parse(date, formatterNew);
System.out.println(dateTimeParkedNew);
}打印时间: 2016-07-09T01:30 2016-07-09T01:30
发布于 2016-07-25 14:54:39
其他答案是正确的,您的字符串是SQL格式,这与规范版本的ISO8601格式不同,它在中间使用空格字符,而不是T。因此,要么用T替换空格,要么定义用于解析的格式化模式。
使用智能对象,而不是哑字符串
但更大的问题是,您将从数据库中检索字符串形式的日期-时间值。您应该将日期-时间类型的数据作为Java中的日期-时间类型进行检索。
对于与JDBC4.2和更高版本兼容的驱动程序,您应该能够将setObject和getObject与java.time对象一起使用。
对于TIMESTAMP WITHOUT TIME ZONE的SQL类型,使用LocalDateTime。对于TIMESTAMP WITH TIME ZONE,根据数据库使用Instant或ZonedDateTime。
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class );存储在数据库中。
myPreparedStatement.setObject( … , ldt ) ;发布于 2016-07-25 12:25:05
尝试此格式化程序:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");我不确定毫秒的部分(如果它超过1个字符的长度)。
https://stackoverflow.com/questions/38559532
复制相似问题