1

Convert string '2018-08-27T16:40:02+08:00' to datetime using DateTimeFormatter

 private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
 String rawDateString = "2018-08-27T16:40:02+08:00"

 DateTimeFormatter dateTimeFormatter = 
 DateTimeFormatter.ofPattern(DATE_TIME_FORMAT, Locale.ENGLISH);
 LocalDateTime localDateTime = LocalDateTime.parse(rawDateString, dateTimeFormatter);
 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

but this returns DateTimeParseException: Text could not be parsed at index 19

I saw some similar issue like this

DateTimeParseException: Text could not be parsed at index 2

but I dont see any sample with timezone on datetime format.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Renz Manacmol
  • 869
  • 12
  • 27
  • 1
    Please also see my comments under this question: [Migrating to Java 8 DateTime \[duplicate\]](https://stackoverflow.com/questions/54031601/migrating-to-java-8-datetime). You don’t need the formatter. But you do need to parse into an `OffsetDateTIme` (a `LocalDateTime` won’t work). `OffsetDateTime odt = OffsetDateTime.parse(rawDateString);`. It also simplifies the conversion: `return Date.from(odt.toInstant());`. In my time zone the result is `Mon Aug 27 10:40:02 CEST 2018`. – Ole V.V. May 20 '20 at 17:48
  • Other than that the answers that are relevant to you are [this one by Basil Bourque](https://stackoverflow.com/a/46017622/5772882) and [this one by deHaar](https://stackoverflow.com/a/56834598/5772882). – Ole V.V. May 20 '20 at 17:54
  • A detail, the exception I get from your code says *Text '2018-08-27T16:40:02+08:00' could not be parsed, unparsed text found at index 19*. – Ole V.V. May 20 '20 at 17:57
  • @OleV.V. I agree with this solution of using OffsetDateTIme to simplify the parsing of date with timezone for this kind of format "2018-08-27T16:40:02+08:00" – Renz Manacmol May 22 '20 at 01:52

1 Answers1

1

You neeed to specify timezone offset in your format as well. Like that:

 String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX";

See the link bellow: https://www.journaldev.com/17899/java-simpledateformat-java-date-format

Sebastian
  • 551
  • 2
  • 8
  • Thanks for the contribution. It’s not incorrect, but (1) the OP doesn’t need a formatter at all, so we don’t need to fix that part. (2) The link is irrelevant since the OP is wisely using java.time, the modern Java date and time API, not the old and troublesome `SimpleDateFormat`. – Ole V.V. May 20 '20 at 17:50