0

I am trying to convert tow format of iso8601 date to localDateTime but this operation seems not working.

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

    public class DemoIsoDate {
        public static void main(String[] args) {
              Instant instant = Instant.parse("2016-08-18T06:17:10.225Z");
              LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
              System.out.println("LocalDateTime in epoch milli : " + ldt.toEpochSecond(ZoneOffset.UTC) * 1000);

              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
              .withZone(ZoneOffset.UTC);

              System.out.println(LocalDateTime.parse("2015-07-17T17:47:18+08:00", dtf));
        }
    }

This is the stacktrace:

LocalDateTime : 1471501030000 Exception in thread "main"
java.time.format.DateTimeParseException: Text '2015-07-17T17:47:18+08:00' could not be parsed at index 16
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at ca.qc.alfred.jms.reader.service.DemoIsoDate.main(DemoIsoDate.java:24)

Is that a problem of pattern that i am using or what ?

Thank you !

VGR
  • 40,506
  • 4
  • 48
  • 63
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
  • This is not localdatetime, it is with offset – Ryuzaki L Jul 31 '19 at 02:12
  • 2
    Your string contains `17:47:18` but your DateTimeFormatter pattern contains `HH:mm` with no seconds. That’s why the exception message says the problem is at index 16, where `:18` starts. – VGR Jul 31 '19 at 02:15
  • 1
    Since, as @VGR said, your string contains seconds, just use `LocalDateTime.parse("2015-07-17T17:47:18+08:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME)`. `DateTimeFormatter.ISO_OFFSET_DATE_TIME` will happily parse strings both with and without seconds. – Ole V.V. Aug 04 '19 at 08:32

1 Answers1

0

Java LocalDateTime class does not accept timezone as an argument, you need to pass an ISO-8601 string: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

You need to convert your string to LocalDateTime and latter convert it to a ZonedDateTime Example:

LocalDateTime ldt = LocalDateTime.parse("2019-07-30T23:21");
ZoneId zoneId = ZoneId.of("America/Sao_Paulo");

ZonedDateTime zdt = ZonedDateTime.of(ldt, zoneId);
Rodrigo Sene
  • 309
  • 1
  • 13