简体   繁体   中英

Convert UTC timestamp to time with offset in Java

I have a MYSQL UTC timestamp "2021-07-23 08:13:17".

I want to convert this to a time with offset eg "2021-07-21T08:13:17+01:00". My code is:

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();

However, the first line gives the error:

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

How can I do this simple conversion?

Your string doesn't have a offset in it, so it's not an OffsetDateTime . It only has a date and a time component, so it's just a LocalDateTime .

LocalDateTime localDateTime = OffsetDateTime.parse("2021-07-23 08:13:17", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

After that, you can give it an offset using atOffset :

OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.ofHours(1));

There is no offset in your String , that means you will have to parse it to a LocalDateTime (a DateTime without an offset) and then add the desired offset.

This code does exactly that:

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);
}

Output:

2021-07-23T08:13:17+01:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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