问题描述
我有一个 MysqL UTC 时间戳“2021-07-23 08:13:17”。
我想将其转换为具有偏移量的时间,例如“2021-07-21T08:13:17+01:00”。我的代码是:
OffsetDateTime offsetDateTime = OffsetDateTime.parse("2021-07-23 08:13:17",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
offsetDateTime.format(ISO_OFFSET_DATE_TIME).toString();
然而,第一行给出了错误:
Text '2021-07-23 08:13:17' Could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2021-07-23T08:13:17 of type java.time.format.Parsed
如何进行这种简单的转换?
解决方法
您的字符串中没有偏移量,因此它不是 OffsetDateTime
。它只有一个日期和一个时间组件,所以它只是一个 LocalDateTime
。
LocalDateTime localDateTime = OffsetDateTime.parse("2021-07-23 08:13:17",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
之后,您可以使用 atOffset
给它一个偏移量:
OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.ofHours(1));
,
您的 String
中没有偏移量,这意味着您必须将其解析为 LocalDateTime
(没有偏移量的 DateTime),然后添加所需的偏移量.
这段代码就是这样做的:
public static void main(String[] args) throws Exception {
String input = "2021-07-23 08:13:17";
// define the formatter for parsing
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss",Locale.ENGLISH);
// then parse to a LocalDateTime and add an offset of +1 hour
OffsetDateTime odt = LocalDateTime.parse(input,dtf)
.atOffset(ZoneOffset.ofHours(1));
System.out.println(odt);
}
输出:
2021-07-23T08:13:17+01:00