0

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;

        }
    }
BAR
  • 15,909
  • 27
  • 97
  • 185
  • 3
    Maybe change your `DateTimeFormatter` to the format that you want? – Scary Wombat Feb 03 '20 at 23:56
  • Does this answer your question? [How to parse a date?](https://stackoverflow.com/questions/999172/how-to-parse-a-date) – itwasntme Feb 04 '20 at 00:09
  • @itwasntme This doesn't work `new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssXXXX")` – BAR Feb 04 '20 at 00:15
  • `OffsetDateTime.parse("2020-02-03T23:40:17+0000", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"))` ==> `2020-02-03T23:40:17Z` – ernest_k Feb 04 '20 at 00:23
  • Similar to above comment try something like `DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXXX");` – itwasntme Feb 04 '20 at 00:25
  • Both ` – FoggyDay Feb 04 '20 at 01:09
  • @FoggyDay While both offset formats are valid in itself, `2020-02-03T23:40:17+0000` is not as it mixes what ISO 8601 calls basic and extended format. – Christian S. Feb 04 '20 at 01:32
  • @Christian S. - and RFC 3399 *requires* ` – FoggyDay Feb 04 '20 at 02:01
  • That doesn't have to do with ISO 8601, it's just the offset pattern that matches OP's format (see [Offset Z](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/format/DateTimeFormatter.html)). – Christian S. Feb 04 '20 at 09:18

1 Answers1

1

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.

Christian S.
  • 877
  • 2
  • 9
  • 20