javadateparsingapache-commons-dateutils

Apache date utils parseDateStrictly method dosen't work properly


DateUtils.parseDateStrictly("28 Sep 2018" , "dd MMMM yyyy")

The format of the above date should be dd MMM yyyy (MMM denotes shorter month) , but MMMM also parses shorter month which causes invalid parsing. I am already using parseDateStrictly method. Any other suggestions ?


Solution

  • java.time

    I recommend that you use java.time for your date and time work. Apache DateUtils was useful once we only had the poorly designed Date and SimpleDateFormat classes to work with. We don’t need it anymore. For a long time now we haven’t needed it.

    java.time behaves the way you expect out of the box.

        DateTimeFormatter dateFormatter
                = DateTimeFormatter.ofPattern("dd MMMM uuuu", Locale.ENGLISH);
        String dateString = "28 Sep 2018";
        LocalDate.parse(dateString, dateFormatter);
    

    Result:

    Exception in thread "main" java.time.format.DateTimeParseException: Text '28 Sep 2018' could not be parsed at index 3
        at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
        at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
        at java.base/java.time.LocalDate.parse(LocalDate.java:428)
        (etc.)
    

    Link

    Oracle tutorial: Date Time explaining how to use java.time.