如何使用SimpleDateFormat解析多种格式的日期 [英] How to parse dates in multiple formats using SimpleDateFormat
问题描述
我正在尝试解析文档中出现的一些日期。看来用户已经输入了相似但不完全相同的格式。
这里是格式:
9/09
9/2009
09/2009
9/1/2009
9-1-2009
最好的方法是尝试解析所有这些?这些似乎是最常见的,但我猜是挂起我的是,如果我有一个M / yyyy的模式,永远在MM / yyyy之前抓到我必须设置我的try / catch块以最严格的限制性方式嵌套最少限制?似乎它肯定会采取大量的代码重复来获得这个权利。
您需要为每个对象使用不同的 SimpleDateFormat
不同的模式也就是说,您不需要许多不同的,感谢这个:
编号:对于格式化,模式字母数是最小位数,较短的数字被零填充到这个数量。为了解析,模式字母的数量将被忽略,除非需要分隔两个相邻的字段。
所以,你需要这些格式:
-
M / y
(涵盖9/09
,9/2009
和09/2009
) -
M / d / y
(涵盖9/1/2009
) -
Mdy
(涵盖9-1-2009
)因此,我的建议是编写一个类似这样的方法(未测试):// ...
String [] formatStrings = {M / y,M / d / y Mdy};
// ...
日期tryParse(String dateString)
{
for(String formatString:formatStrings)
{
try
{
返回新的SimpleDateFormat(formatString).parse(dateString);
}
catch(ParseException e){}
}
返回null;
}
I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.
here are the formats: 9/09 9/2009 09/2009 9/1/2009 9-1-2009
What is the best way to go about trying to parse all of these? These seem to be the most common, but I guess what is hanging me up is that if i have a pattern of "M/yyyy" wont that always catch before "MM/yyyy" Do I have to set up my try/catch blocks nested in a least restrictive to most restrictive way? it seems like it sure is going to take a lot of code duplication to get this right.
解决方案You'll need to use a different
SimpleDateFormat
object for each different pattern. That said, you don't need that many different ones, 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.
So, you'll need these formats:
"M/y"
(that covers9/09
,9/2009
, and09/2009
)"M/d/y"
(that covers9/1/2009
)"M-d-y"
(that covers9-1-2009
)
So, my advice would be to write a method that works something like this (untested):
// ... String[] formatStrings = {"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; }
这篇关于如何使用SimpleDateFormat解析多种格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!