Apache dateutils parseDate Strictly 方法无法正常工作

Apache date utils parseDateStrictly method dosen't work properly

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

上面的日期格式应该是dd MMM yyyy(MMM表示较短的月份),但是MMMM也会解析较短的月份,导致解析无效。我已经在使用 parseDateStrictly 方法。还有其他建议吗?

java.time

我建议您使用 java.time 作为您的日期和时间工作。 Apache DateUtils 在我们只有设计糟糕的 DateSimpleDateFormat 类 时很有用。我们不再需要它了。很长一段时间以来我们都不需要它。

java.time 开箱即用。

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

结果:

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 解释如何使用 java.time。

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.

使用现代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.");
            }
        }
    }
}

输出:

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

Trail: Date Time.

了解有关现代 date-time API 的更多信息

如果您正在为您的 Android 项目执行此操作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring and .