【问题标题】:Date time parsing that accepts 05/05/1999 and 5/5/1999, etc接受 05/05/1999 和 5/5/1999 等的日期时间解析
【发布时间】:2010-09-18 15:53:29
【问题描述】:

有没有一种简单的方法来解析可能是 MM/DD/yyyy、M/D/yyyy 或某种组合的日期?即,在一位数的日期或月份之前,零是可选的。

要手动完成,可以使用:

String[] dateFields = dateString.split("/");
int month = Integer.parseInt(dateFields[0]);
int day = Integer.parseInt(dateFields[1]);
int year = Integer.parseInt(dateFields[2]);

并通过以下方式验证:

dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d")

是否有调用 SimpleDateFormat 或 JodaTime 来处理这个问题?

【问题讨论】:

    标签: java date time parsing


    【解决方案1】:

    java.time

    Java 8 及更高版本包括 java.time 框架。该框架淘汰了此处其他答案中讨论的旧 java.util.Date/.Calendar 类。

    java.time.format 包及其 java.time.format.DateTimeFormatter 类使用类似于 Ray Myers 在accepted Answer 中看到的模式代码。虽然相似,但它们略有不同。特别是他们对重复字符的数量非常严格。如果你说MM,那么月份必须填充为零,否则你会得到DateTimeParseException。如果月份编号可能有也可能没有填充零,只需使用单字符 M

    在此示例代码中,请注意输入字符串的月份编号如何填充零,而月份编号则没有。两者都由单字符模式处理。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/yyyy" );
    LocalDate localDate = formatter.parse ( "01/2/2015" , LocalDate :: from );
    

    转储到控制台。

    System.out.println ( "localDate: " + localDate );
    

    本地日期:2015-01-02

    【讨论】:

      【解决方案2】:

      看起来我的问题是使用“MM/DD/yyyy”,而我应该使用“MM/dd/yyyy”。大写D是“年中的日子”,而小写d是“月中的日”。

      new SimpleDateFormat("MM/dd/yyyy").parse(dateString);
      

      完成这项工作。此外,“M/d/y”可以互换使用。仔细阅读SimpleDateFormat API Docs 会发现以下内容:

      “在解析时,模式字母的数量将被忽略,除非需要分隔两个相邻的字段。”

      【讨论】:

        【解决方案3】:

        是的,使用 setLenient:

        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        df.setLenient(true);
        System.out.println(df.parse("05/05/1999"));
        System.out.println(df.parse("5/5/1999"));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-27
          相关资源
          最近更新 更多