[英]Generic DateTimeFormatter pattern for ISO 8601 datetime string with zone offset
I have a list of ISO 8601
date strings that I want to parse and convert to OffsetDateTime
.我有一个要解析并转换为OffsetDateTime
的ISO 8601
日期字符串列表。
Below is how I am converting:以下是我的转换方式:
var date = OffsetDateTime.parse("2013-03-13T20:59:31-08:00");
This works totally fine but there are some dates in the list that don't have :
in the Zone offset
, therefore, I am getting the following exception from the parser.这工作得很好,但列表中有一些日期没有:
在Zone offset
中,因此,我从解析器中得到以下异常。
var date = OffsetDateTime.parse("2013-03-13T20:59:31-0800"); // no `:` in the zone offset
------> java.time.format.DateTimeParseException: Text '2013-03-13T20:59:31-0800' could not be parsed, unparsed text found at index 22
I was able to solve this problem using the updated parser below:我能够使用下面更新的解析器解决这个问题:
var date = OffsetDateTime.parse("2013-03-13T20:59:31-0800", DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ"));
But this is not helping as this parser is now not converting the first date ie 2013-03-13T20:59:31-08:00
(with :
) and throwing the exception但这无济于事,因为此解析器现在未转换第一个日期,即2013-03-13T20:59:31-08:00
(带有:
)并抛出异常
-----> java.time.format.DateTimeParseException: Text '2013-03-13T20:59:31-08:00' could not be parsed at index 19
As per my understanding from Wikipedia , both the dates seem to be in ISO 8601
format and should be converted via a single parser.根据我对Wikipedia的理解,这两个日期似乎都是ISO 8601
格式,应该通过单个解析器进行转换。 Unfortunately, I could not find any common function and would like to understand how to tackle this situation?不幸的是,我找不到任何常见的 function 并且想了解如何解决这种情况?
I really don't want to manipulate the date string (maybe using regex etc) before passing it to the parser.我真的不想在将日期字符串传递给解析器之前对其进行操作(可能使用正则表达式等)。
[]
is how you introduce optional stuff. []
是介绍可选内容的方式。
I had to toy around with stuff for quite a while to make this work, but, you can:为了完成这项工作,我不得不摆弄一些东西,但是,你可以:
var pattern = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss[XXXX][XXXXX]");
var date = OffsetDateTime.parse("2013-03-13T20:59:31-0830", pattern));
System.out.println(date);
var date2 = OffsetDateTime.parse("2013-03-13T20:59:31-08:30", pattern));
System.out.println(date2);
XXXX
is the pattern for -0800, XXXXX
is for -08:00. XXXX
是-0800 的模式, XXXXX
是-08:00 的模式。
By making them both optional, the 'right one' will be used.通过使它们都是可选的,将使用“正确的”。
EDIT: I had a completely different answer at first, that didn't actually work.编辑:起初我有一个完全不同的答案,但实际上并没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.