java - 如何使用 SimpleDateFormat 解析多种格式的日期

标签 java parsing datetime simpledateformat

我正在尝试解析来自文档的一些日期。用户似乎以类似但不准确的格式输入了这些日期。

格式如下:

9/09
9/2009
09/2009
9/1/2009
9-1-2009 

尝试解析所有这些的最佳方法是什么?这些似乎是最常见的,但我想让我感到困惑的是,如果我有一个“M/yyyy”模式,它不会总是在“MM/yyyy”之前捕获我是否必须设置我的 try/catch block 以最少限制到最多限制的方式嵌套?似乎肯定需要大量的代码重复才能做到这一点。

最佳答案

您需要为每个不同的模式使用不同的 SimpleDateFormat 对象。也就是说,你不需要那么多不同的,thanks to this :

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

所以,你需要这些格式:

  • "M/y"(涵盖 9/099/200909/2009)
  • "M/d/y"(涵盖9/1/2009)
  • “M-d-y”(涵盖9-1-2009)

所以,我的建议是编写一个像这样工作的方法(未经测试):

// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...

Date tryParse(String dateString)
{
    for (String formatString : formatStrings)
    {
        try
        {
            return new SimpleDateFormat(formatString).parse(dateString);
        }
        catch (ParseException e) {}
    }

    return null;
}

关于java - 如何使用 SimpleDateFormat 解析多种格式的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024544/

相关文章:

html - 在 Dart 中将 HTML 字符串解析为 DOM

使用 Swift 读取文本文件的 Pythonic 方式

c# - "Syntax error in INSERT INTO statement"错误,当我尝试通过 C# 将日期插入到 Access 数据库时

javascript - 如何以 HH :MM:SS? 格式在 JavaScript 中显示当前时间

java - 替换字符串 Java

Java多线程: Fast alternative to AtomicInteger wanted

java - 使用 GSON 将字符串解析为 JsonObject 给出 IllegalStateException : This is not a JSON Object

java - 为什么满足 "if ... <=0"标准时没有任何反应?

parsing - 如何解析依赖于父节点信息的子节点?

android - 如何检查 "Automatic date and time"是否启用?