Search code examples
javasimpledateformat

SimpleDateFormat not parsing IST date


I'm trying to parse this date: Mon, 05 Jul 2021 23:19:58 IST

String date = "Mon, 05 Jul 2021 23:19:58 IST";
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.getDefault());
dateFormat.parse(date);

But I'm getting this error: java.text.ParseException: Unparseable date: "Mon, 05 Jul 2021 23:19:58 IST"

When I omit the lowercase z from the format, I don't get the exception, but the date isn't in the correct timezone. I've tried doing the following:

dateFormat.setTimeZone(TimeZone.getTimeZone("IST"));

But the date still shows in the future, which is incorrect. How can I correctly parse this date? Thank you.


Solution

  • Don't use Date or SimpleDateTime. Use the classes in the java.time package.

    String date = "Mon, 05 Jul 2021 23:19:58 IST";
    
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(
            "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    ZonedDateTime zdt = ZonedDateTime.parse(date,dateFormat);
    System.out.println(zdt.format(dateFormat));
    

    prints

    Mon, 05 Jul 2021 23:19:58 GMT
    
    

    EDIT

    After perusing the java.time package I found that ZoneId.SHORT_IDS contained IST=Asia/Kolkata. So if one does the following:

    ZonedDateTime zdt = ZonedDateTime.parse(date,dateFormat)
                  .withZoneSameLocal(ZoneId.of("Asia/Kolkata"));
    System.out.println(zdt.format(dateFormat));
    

    It prints

    Mon, 05 Jul 2021 23:19:58 IST