小编Chr*_* G.的帖子

为什么 SimpleDateFormat.parse 不会在这里抛出异常?

首先,请注意我在这里坚持使用 java6。

我正在尝试从可能采用不同格式的字符串中获取日期。出于某种原因,我没有得到 ParseException ,我希望有一个......

    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class test1{

      public static void main(String argc[]){
          System.out.println(parseAllDateFormats(argc[0]));
    }

      private static final String[] dateFormats = "yyyyMMdd,yyyy/MM/dd,yyyy-MM-dd,dd/MM/yyyy,dd-MM-yyyy,dd-MMM-yyyy,yyyy MM dd".split(",");
      public static Date parseAllDateFormats(String date) {
          if (date == null)
              return null;
          for (int f = 0; f < dateFormats.length; f++) {
              String format = dateFormats[f];
              try {
                  SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    System.out.println("trying " + format);                
                  return dateFormat.parse(date);
              }
              catch (Exception e) {}
          }
          return null;
      }

    }
Run Code Online (Sandbox Code Playgroud)

运行:java test1 1980-04-25 …

java simpledateformat

3
推荐指数
1
解决办法
987
查看次数

标签 统计

java ×1

simpledateformat ×1