Search code examples
javaoracle-databasedatejava-8datetimeformatter

Java 8 – DateTimeFormatter: formatting Oracle dates


I have this function:

private static boolean isDate(String rowData, String pattern) {

    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.getDefault());
        LocalDate.parse(rowData, formatter).atStartOfDay(ZoneId.systemDefault()).toInstant();
        return true;

    } catch (Exception e) {
        return false;

    }

}

and

private static final String ORACLE_DATE_FORMAT1 = "MMM d, yyyy";
private static final String ORACLE_DATE_FORMAT2 = "dd MMM yyyy";

System.out.println("<--------------------------->");
System.out.println("value -> " + value);
System.out.println("isDate -> " + (isDate(value, ORACLE_DATE_FORMAT1) || isDate(value, ORACLE_DATE_FORMAT2)));
System.out.println("<--------------------------->");

but I get this result:

value -> 1 Aug 2020
isDate -> false
<--------------------------->
<--------------------------->
value -> 31 Jul 2099
isDate -> true

Solution

  • This works if you change ORACLE_DATE_FORMAT2 to d MMM yyyy. As per the documentation, when the date is specified as dd, it expects a 2-character representation of the day of the month (e.g. 01 Aug 2020).

    Note that this change will pick up both 1 Aug 2020 and 01 Aug 2020 successfully.

    <--------------------------->
    value -> 01 Aug 2020
    isDate -> true
    <--------------------------->
    
    <--------------------------->
    value -> 1 Aug 2020
    isDate -> true
    <--------------------------->