BAR
BAR

Reputation: 17121

Parse ISO-8601 Datetime

It seems the proper form of timestamp to parse ISO-8601 in Java looks like:

"2020-02-03T23:40:17+00:00";

However mine looks like:

"2020-02-03T23:40:17+0000";

How can I parse this properly?

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

 public class TestTime {
        public static void main(String[] args) {

            String ts = "2020-02-03T23:40:17+0000";
            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);
            long timestamp = offsetDateTime.toEpochSecond() * 1000;

        }
    }

Upvotes: 0

Views: 217

Answers (1)

Christian S.
Christian S.

Reputation: 982

You could pass a pattern to the DateTimeFormatter:

String ts = "2020-02-03T23:40:17+0000";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZZZ");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);

Note that the correct pattern for the offset is ZZZ instead of X or XXXX, which becomes obvious when, for example, formatting the parsed date-time back to a string:

DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);
System.out.println(offsetDateTime.format(timeFormatter));
2020-02-03T23:40:17Z

While when using ZZZ, it will format like 2020-02-03T23:40:17+0000. See the documentation for DateTimeFormatter.

Upvotes: 1

Related Questions