1

I am trying to parse date string to OffsetDateTime as below.

But I am getting below exception,

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon Jun 18 00:00:00 IST 2012' could not be parsed at index 0

public class ParseExample {
    public static void main(String... args) throws ParseException {
        String dateStr = "Mon Jun 18 00:00:00 IST 2012";
        System.out.println(OffsetDateTime.parse(dateStr));
    }
}

can someone please help me with this mistake.

Thanks.

xingbin
  • 27,410
  • 9
  • 53
  • 103
user1660325
  • 747
  • 4
  • 20
  • 35
  • 1
    If you can, avoid relying on parsing a three letter time zone abbreviation like `IST`. You may get Icelandic standard time, Irish summer time, Israel standard time or something else. – Ole V.V. Feb 17 '19 at 16:04
  • 2
    It may look like you’ve got the result of calling `toString` on an old-fashioned `java.util.Date` object? If so, it is better to convert the `Date` to `OffsetDateTime` than to parse its `toString`. `yourOldfashionedDate.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime()`. – Ole V.V. Feb 17 '19 at 16:20
  • Related: [How to convert Date.toString back to Date?](https://stackoverflow.com/questions/9431927/how-to-convert-date-tostring-back-to-date) There’s a longer list of linked questions to the right, you may want to go through it. – Ole V.V. Feb 17 '19 at 16:27

1 Answers1

13

ZonedDateTime

Mon Jun 18 00:00:00 IST 2012 should be a ZonedDateTime, you can parse it with a custom DateTimeFormatter, then convert it to OffsetDateTime:

DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);

OffsetDateTime offsetDateTime = ZonedDateTime.parse(dateStr, format).toOffsetDateTime();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • You should add a note about the risks inherent in trying to parse a non-unique pseudo-zone such as `IST`. Could be India Standard Time, Ireland Standard Time, or others. Instead use real time zone names in standardized `Continent/Region` format such as `Asia/Kolkata`. – Basil Bourque Feb 17 '19 at 21:52