Unable to parse date YYYY-MM-DDThh:mm:ssTZD from string using DateUtils.parseDate

1k views Asked by At

Having date as string: "2021-09-11T12:02:50-06:00Z". Want to convert to java.util.Date using apache DateUtils:

    public static Date toDate (String dateString) throws ParseException {
        String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'TZD''Z'";
        return DateUtils.parseDate(dateString, new String[]{DATETIME_FORMAT});
    }

giving below exception:

java.text.ParseException: Unable to parse the date: 2021-09-11T12:02:50-06:00Z
    at org.apache.commons.lang3.time.DateUtils.parseDateWithLeniency(DateUtils.java:388)
    at org.apache.commons.lang3.time.DateUtils.parseDate(DateUtils.java:302)
    at org.apache.commons.lang3.time.DateUtils.parseDate(DateUtils.java:279)

tried DATETIME_FORMAT as "yyyy-MM-dd'T'HH:mm:ss'TZD''Z'" , "yyyy-MM-dd'T'HH:mm:ss'TZD''Z'", "YYYY-MM-DD'T'hh:mm:ss'TZD'"

1

There are 1 answers

2
Prabir Ghosh On BEST ANSWER

Please make this correction in format and also in date string.

public static Date toDate (String dateString) throws ParseException {
        String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
        return DateUtils.parseDate(dateString, new String[]{DATETIME_FORMAT});
    }

And in input format do not use colon. Example

 System.out.println(toDate  ("2021-09-11T12:02:50-0600"));