java.time.format.DateTimeParseException:无法在索引21处解析文本

day*_*mer 21 java datetime java-8 java-time

我得到的日期时间值为

created_at  '2012-02-22T02:06:58.147Z'
Read-only. The time at which this task was created.
Run Code Online (Sandbox Code Playgroud)

这是由Asana API提供的

Java 8用来解析日期时间如下

import java.time.*;
import java.time.format.*;

public class Times {

  public static void main(String[] args) {
    final String dateTime = "2012-02-22T02:06:58.147Z";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss.SX");


    final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
    System.out.println(parsed);
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '2012-02-22T02:06:58.147Z' could not be parsed at index 21
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
    at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
    at Times.main(Times.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Run Code Online (Sandbox Code Playgroud)

什么不对吗?

ass*_*ias 22

默认解析器可以解析您的输入.所以你不需要自定义格式化器

String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);
Run Code Online (Sandbox Code Playgroud)

按预期工作.


Rom*_*man 19

如果您的输入始终具有"zulu"("Z"= UTC)的时区,则可以使用DateTimeFormatter.ISO_INSTANT(隐式):

final Instant parsed = Instant.parse(dateTime);
Run Code Online (Sandbox Code Playgroud)

如果时区变化并且形式为"+01:00"或"+01:00:00"(当不是"Z"时),则可以使用DateTimeFormatter.ISO_OFFSET_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
Run Code Online (Sandbox Code Playgroud)

如果不是这种情况,您可以按照构造的DateTimeFormatter方式构造a DateTimeFormatter.ISO_OFFSET_DATE_TIME.


您当前的模式有几个问题:

  • 不使用严格模式(ResolverStyle.STRICT);
  • 使用yyyy而不是uuuu(yyyy不会在严格模式下工作);
  • 使用12小时hh而不是24小时HH;
  • 仅使用一位数S表示小数秒,但输入有三位数.