繁体   English   中英

将UTC时间戳转换为Java中的偏移量时间

[英]Convert UTC timestamp to time with offset in Java

我有一个 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM