问题描述
字符串采用这种格式 - "2021-07-13 05:22:18.712"
我尝试使用此代码来解析它。
OffsetDateTime parsedDateTime = OffsetDateTime.parse("2021-07-13 05:22:18.712");
但我不断收到此错误 - org.threeten.bp.format.DateTimeParseException: 无法在索引 10 处解析文本“2021-07-13 05:22:18.712”。
我如何使它工作?任何建议都会有所帮助。谢谢
解决方法
您需要确定时区(或至少确定偏移量,但时区通常是正确的方法)。然后您需要使用一个格式化程序来定义您要解析的格式:
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter(Locale.ROOT);
使用此格式化程序,操作非常简单:
ZoneId zone = ZoneId.of("Asia/Kolkata");
String input = "2021-07-13 05:22:18.712";
OffsetDateTime dateTime = LocalDateTime.parse(input,FORMATTER)
.atZone(zone)
.toOffsetDateTime();
System.out.println(dateTime);
示例代码段的输出是:
2021-07-13T05:22:18.712+05:30
由于@Sweeper 在评论中指出您的字符串不包含 UTC 偏移量和时区,因此首先将其解析为 LocalDateTime
。某些 java.time 类名称中的 Local
表示没有时区或 UTC 偏移量。然后转换为预期时区中的 ZonedDateTime
并进一步转换为所需类型 OffsetDateTime
。
如果要使用 JVM 的默认时区,请将 zone
设置为 ZoneId.systemDefault()
。请注意,您的程序的其他部分或同一 JVM 中运行的其他程序可能会随时更改默认时区,因此这很脆弱。
可能的快捷方式
我的格式化程序很冗长,因为我想尽可能多地重复使用内置格式化程序。如果您不介意从模式中手动构建格式化程序,您可以使用:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS",Locale.ROOT);
或者更短,您可以用 T
手动替换字符串中的空格以获得 ISO 8601 格式,然后解析为 LocalDateTime
,根本不指定任何格式化程序。
您的代码出了什么问题?
您收到的异常消息试图提供帮助:
但我不断收到此错误 - org.threeten.bp.format.DateTimeParseException: 文本 '2021-07-13 05:22:18.712' 无法在索引 10 处解析。
字符串中的索引 10 是日期和时间之间的空格所在的位置。 one-arg OffsetDateTime.parse
方法需要 ISO 8601 格式,如 2021-07-13T05:22:18.712+05:30
,因此使用 T
表示时间部分的开始,并在结束时使用 UTC 偏移量。 T
的缺失导致了您的异常。如果你解决了这个问题,你会因为缺少 UTC 偏移量而得到另一个异常。
链接
,您首先需要检查 document。
表示解析需要使用日期格式,例如 2007-12-03T10:15:30 +01:00。
您的约会对象缺少“T”、“2021-07-13 05:22:18.712”。因此它并不顺利,从索引 0 开始计算,它的字符在 10。
如果你需要解析2021-07-13T05:22:18.712,你仍然会得到错误。在索引 23 处无法解析错误文本 '2021-07-13T05:22:18.712'。这是毫秒的问题。
还有一个大回合:
//Format to date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//Format to new string
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
java.util.Date date1=simpleDateFormat.parse("2021-07-13 05:22:18.712");
String newDate = formatter.format(date1);
//finally.
OffsetDateTime parsedDateTime = OffsetDateTime.parse(newDate);