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

查看:955
本文介绍了如何使用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 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):

    // ...
    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屋!

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