如何使用 SimpleDateFormat 解析多种格式的日期 [英] How to parse dates in multiple formats using SimpleDateFormat

查看:41
本文介绍了如何使用 SimpleDateFormat 解析多种格式的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这里是格式:

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

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

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.

推荐答案

您需要为每个不同的模式使用不同的 SimpleDateFormat 对象.也就是说,您不需要那么多不同的,感谢这个:

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"(包括 9/099/200909/2009>)
  • "M/d/y"(涵盖 9/1/2009)
  • "M-d-y"(涵盖9-1-2009)
  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

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

So, my advice would be to write a method that works something like this (untested):

// ...
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;
}

这篇关于如何使用 SimpleDateFormat 解析多种格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆