在Java中将字符串转换为OffsetDateTime

我试图在OffsetDateTime转换一个字符串,但低于错误。

java.time.format.DateTimeParseException: Text '20150101' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2015-01-01 of type java.time.format.Parsed

代码: OffsetDateTime.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

预期输出: OffsetDateTime object with date 20150101.

我非常感谢您提供的任何帮助。

谢谢,

OffsetDateTime表示具有偏移的日期时间,例如。

2007-12-03T10:15:30 + 01:00

您尝试解析的文本不符合OffsetDateTime.的要求OffsetDateTime. 请参阅https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html

被解析的字符串既不包含ZoneOffset也不包含时间。 从字符串和格式化程序的模式,看起来你只需要一个LocalDate。 所以,你可以使用:

 LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd")); 

对于您的情况使用LocalDate而不是offsetDatetime,因为您只想解析日期(没有时间/偏移)。 这里非常好地讨论了offsetDatetime的用法

谢谢大家的回复。 之前我使用joda datetime(查看下面的方法)来处理日期和日期时间,但我想使用Java8库而不是外部库。

 static public DateTime convertStringInDateFormat(String date, String dateFormat){ DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat); return formatter.parseDateTime(date); } 

我期待与OffsetDateTime相同,但是如果我们想在某个时区使用日期/时间,我们就知道我们可以使用ZonedDateTime或OffsetDateTime。 当我正在处理LocalDate可以提供帮助的时段和持续时间。

字符串到DateTime:

 LocalDate date = LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd")); 

LocalDate到所需的字符串格式:

 String dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; date.atStartOfDay().format(DateTimeFormatter.ofPattern(dateFormat));