1

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
crmepham
  • 4,676
  • 19
  • 80
  • 155

3 Answers3

3

I guess you should use "h" instead of "H". Lowercase h refers to 0-12 capital one refers to 0-24. Overall it should be MMM d, yyyy, hh:mm:ss a

cool
  • 1,746
  • 1
  • 14
  • 15
3

If you change the SimpleDateFormat to DateTimeFormatter the exception shows the error:

Caused by: java.time.DateTimeException: Conflict found: Field AmPmOfDay 1 differs from AmPmOfDay 0 derived from 12:00

For the 12:00 time it expects it to be PM. if you mean midnight instead, it should be 00:00 AM.

MarianP
  • 2,719
  • 18
  • 17
2

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

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97