javadatesimpledateformatdatetime-parsingparseexception

ParseException while parsing date from String to date Object


I'm getting a ParseException while parsing a date from String to Date object. The date string also contains a timezone. I'm using this code:

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
System.out.print(sdf.parse("2018-01-16T00:07:00.000+05:30"));

Below is the error I'm getting:

Exception in thread "main" java.text.ParseException: Unparseable date: "2018-01-16T00:07:00.000+05:30"
    at java.text.DateFormat.parse(DateFormat.java:366)

Solution

  • The format you use in SimpleDateFormat must match the input String.

    Your input is 2018-01-16T00:07:00.000+05:30, which is ISO8601 compliant:

    Note: the offset +05:30 is not a timezone. Read this to know the difference.

    Anyway, the pattern you're using ("yyyy-MM-dd HH:mm:ss z") doesn't match the input string:

    So your code should be:

    // use "XXX" to parse the whole offset (only one "X" will parse just `+05`, missing the `:30` part)
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    Date d = sdf.parse("2018-01-16T00:07:00.000+05:30");
    

    But it's much better to use the new Java 8 classes, if they're available to you:

    // parse ISO8601 compliant string directly
    OffsetDateTime odt = OffsetDateTime.parse("2018-01-16T00:07:00.000+05:30");
    

    If you still need to use a java.util.Date object, it's easy to convert:

    // convert to java.util.Date
    Date date = Date.from(odt.toInstant());