Search code examples
javadatesimpledateformatdateparser

Unparsable date format


I am attempting to parse a date String but get this error:

java.text.ParseException: Unparseable date: "Oct 1, 1997, 12:00:00 AM"

This is the method I am using to parse the Date:

public static Date parse(@NonNull String dateString, @NonNull String dateFormat) {
    val sdf = new SimpleDateFormat(dateFormat);
    sdf.setLenient(false);
    try {
        return sdf.parse(dateString);
    } catch (ParseException e) {
        return null;
    }
}

Where the dateString is Oct 1, 1997, 12:00:00 AM and the dateFormat is MMM d, yyyy, HH:mm:ss a.

Why is it failing to parse the date?


Solution

  • your code is throwing an exception because the string Date is not valid for the string pattern, look in the doc here

    concretely, if the hour is in a format between 0-23 then the string is HH, but if you use a 1-12 AM, PM then you have to use hh

    here is some ref code:

    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            Date x = parse("Oct 1, 1997, 12:00:00 AM", "MMM d, yyyy, hh:mm:ss a");
            System.out.println("X String: " + x); 
        }
        
        public static Date parse(String dateString, String dateFormat) {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            sdf.setLenient(false);
            try {
                return sdf.parse(dateString);
            } catch (Exception e) {
                System.out.println("E???");
                return null;
            }
        }
    }
    

    and if you need to edit, here the ideone code:

    https://ideone.com/ccwo2Y