使用 Resultset 将数据库中的字符串变量(日期时间类型)解析为 LocalDateTime 变量

parse String variable from database (type datetime) to LocalDateTime variable using Resultset

我正在尝试转换存储在数据库中(作为日期时间)的字符串值(最初是 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 是日期和时间之间的 space。

谁能帮我解决这个问题?我已经花了好几个小时了:(

试试这个格式化程序:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");

虽然我不确定毫秒部分(以防它超过 1 个字符长)。

导致该问题的格式有误。请参考 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.The ISO 日期时间格式为 '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

其他答案是正确的,您的字符串采用 SQL 格式,这与 ISO 8601 格式的规范版本不同,中间使用 space 字符而不是 T.因此,要么将 space 替换为 T,要么定义用于解析的格式化模式。

使用智能对象,而不是哑字符串

但更大的问题是您正在从数据库中以字符串形式检索日期时间值。您应该将日期时间类型的数据检索为 Java 中的日期时间类型。

对于兼容 JDBC 4.2 及更高版本的驱动程序,您应该能够将 setObjectgetObject 与 java.time 对象一起使用。

对于 SQL 类型的 TIMESTAMP WITHOUT TIME ZONE 使用 LocalDateTime。对于 TIMESTAMP WITH TIME ZONE,根据数据库使用 InstantZonedDateTime

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class );

存储在数据库中。

myPreparedStatement.setObject( … , ldt ) ;