Apache date utils parseDateStrictly method dosen't work properly

510 Views Asked by At
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 ?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

The column format is dd MMMM yyyy and it should parse dates like 28 September 2018 and should throw error on values such as 28 Sep 2018

DateUtils uses the date-time API of java.util and their formatting API, SimpleDateFormat which are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API.

Using the modern date-time API:

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] arr = { "28 September 2018", "28 Sep 2018", "28 09 2018" };
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM uuuu", Locale.ENGLISH);
        for (String s : arr) {
            try {
                LocalDate date = LocalDate.parse(s, formatter);
                // ...Process date e.g.
                System.out.println(DateTimeFormatter.ofPattern("MMMM dd, uuuu", Locale.ENGLISH).format(date));
            } catch (DateTimeException e) {
                System.out.println(s + " is not a valid string.");
            }
        }
    }
}

Output:

September 28, 2018
28 Sep 2018 is not a valid string.
28 09 2018 is not a valid string.

Learn more about the modern date-time API at Trail: Date Time.

If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.