java.time.format.DateTimeParseException:尝试解析时区日期时间时

java.time.format.DateTimeParseException: when trying to parse timezoned datetime

我收到一个带时区的日期时间字符串,我想将其格式化为 LocalDateTime 以将其作为字段 timestamptz 保存在 Postgre 中,但 Java 无法对其进行格式化。我的意思是我想以与收到的格式相同的格式保存。

我试图用 DateTimeFormatter 格式化它,但它抛出 DateTimeParseException。

这是收到的字符串:2019-09-02T11:47:50.877+0200 并尝试像这样格式化:

String datetimeString = "2019-09-02T11:47:50.877+0200";
String pattern = "yyyy-MM-dd\'T\'HH:mm:ss.SSS Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

 LocalDateTime created = (LocalDateTime.from(formatter.parse(datetimeString )));

我希望这样:2019-09-02T11:47:50.877+0200 但它抛出异常。 java.time.format.DateTimeParseException: Text '2019-09-02T11:47:50.877+0200' could not be parsed at index 23

您需要将字符串模式更改为 "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"

String s="2019-09-02T11:47:50.877+0200";

String client = s;
    String cttdate = "";
    char[] c = client.toCharArray();
    for (int i = 0; i < 10; i++) {      
        cttdate = cttdate + c[i];           // Getting  Client UTC Date as a String From String
    }
    int ctdate = Integer.valueOf(cttdate.replaceAll("-", "")); //Replace All Special Symbol From Client Date For Compare

    String cttime = "";
    for (int i = 11; i <= 15; i++) {
        cttime = cttime + c[i];             // Getting  Client UTC Time as a String From String
    }
    Date ctime = sdf.parse(cttime);

仔细阅读异常消息

这是一个计数练习。

java.time.format.DateTimeParseException: Text '2019-09-02T11:47:50.877+0200' could not be parsed at index 23

索引 23 是 +(加号)在您的日期时间字符串中的位置。所以就在毫秒之后。将此与您的格式模式字符串进行比较:

String pattern = "yyyy-MM-dd\'T\'HH:mm:ss.SSS Z";

毫秒后有一个 space,它不在您要解析的字符串中。格式模式字符串中的 space 意味着解析器在日期时间字符串和对象中找不到 space,但找不到。删除 space,您的字符串将被解析为 2019-09-02T11:47:50.877.

顺便说一句,考虑使用 OffsetDateTime 而不是 LocalDateTime。第一,LocalDateTime 没有太多用处,因为它没有定义时间点。第二,通常最好从日期时间字符串中获取我们可以获取的所有信息,并且您的字符串确实包含一个偏移量。以后丢弃信息会更容易(遗憾的是,根据经验,很容易发明错误的信息来替换我们忘记从字符串中保留的正确信息,请尽量避免这种陷阱)。第三,根据文档,PostgreSQL JDBC 驱动程序确实需要 OffsetDateTime 而不是 LocalDateTime 作为 timestamp with timezone 列。请参阅下面的 link。

相关问题及其他link

Using Java 8 Date and Time classes 在 PostgreSQL JDBC 驱动程序手册中。

你的格式是ISO 8601,同样的格式解析还有其他问题(感谢@Vignesh_A第一个link):

  • (go for )