我正在尝试解析来自文档的一些日期。用户似乎以类似但不准确的格式输入了这些日期。
格式如下:
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/09
、9/2009
和09/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/