【问题标题】:DateTimeFormatter Support for Single Digit Day of Month and Month of YearDateTimeFormatter 支持一位数的月份日期和年份月份
【发布时间】:2015-02-18 16:53:51
【问题描述】:

DateTimeFormmater 似乎无法处理月份中的一位数日期:

String format = "MM/dd/yyyy";
String date   = "5/3/1969";
System.out.println(new SimpleDateFormat(format).parse(date));
System.out.println(LocalDate.parse(date, DateTimeFormatter.ofPattern(format)));

在本例中,SimpleDateFormat 正确解析日期,但DateTimeFormatter 抛出异常。如果我要使用零填充日期,例如“05/03/1969”,那么两者都可以。但是,如果某月的某天或某年的月份是个位数,则DateTimeFormatter 会引发异常。

什么是正确的DateTimeFormatter 格式来解析月份和月份的一位和两位数?

【问题讨论】:

  • 您解决了这个问题吗?我也在寻找一个 java8 解决方案来解析 1 或 2 位数的月份,或 2 或 4 位数的年份。

标签: java date java-8 java-time


【解决方案1】:

来自the documentation

数字:如果字母数为 1,则使用最小位数输出该值且不进行填充。

所以你想要的格式说明符是M/d/yyyy,使用单字母形式。当然,它仍然会像"12/30/1969" 一样正确解析日期Strings,因为对于这些日/月值,两位数是“最小位数”。

重要的区别在于 MMdd 需要零填充,而不是 Md 不能处理大于 9 的值(这有点……不寻常)。

【讨论】:

  • 我在 Dart 中遇到了同样的问题,但是使用 intl 包实现了上述解决方案,它现在可以正常工作。谢谢。
  • 这个很有效,很好地解释了@Holger。文档链接也很有帮助。
【解决方案2】:

最近在Java 8 Date Time API中使用

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendOptional(DateTimeFormatter.ofPattern("M/dd/yyyy"))
            .toFormatter();

System.out.println(LocalDate.parse("10/22/2020", formatter));
System.out.println(LocalDate.parse("2/21/2020", formatter));

【讨论】:

  • 为什么要包含第二个模式?您希望第二个而不是第一个解析什么值?
  • @JonSkeet 你的建议很好。我刚刚删除了第二个模式,因为单个模式能够解析两种类型的值,例如 10/22/2020 和 2/22/2020
  • 这是一个很好的解决方案。我可以添加多种模式。谢谢
【解决方案3】:

处理此类问题的最佳方法,即日期(日、月或年)中不同数字的数量是使用这种模式:(M/d/[uuuu][uu] ) .

例子:

String date = "7/7/2021"; // or "07/07/2021" or "07/7/21" etc
LocalDate localDate = LocalDate.parse(
date,DateTimeFormatter.ofPattern("M/d/[uuuu][uu]"));

这里 uuuu/uu 处理四位数和两位数的年份。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2021-12-16
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多