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

Chr*_* G. 3 java simpledateformat

首先,请注意我在这里坚持使用 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

我希望得到:

trying yyyyMMdd
trying yyyy/MM/dd
trying yyyy-MM-dd
Fri Apr 25 00:00:00 EST 1980
Run Code Online (Sandbox Code Playgroud)

但我只得到:

trying yyyyMMdd
Tue Dec 04 00:00:00 EST 1979
Run Code Online (Sandbox Code Playgroud)

知道出了什么问题吗?

小智 6

SimpleDateFormat 默认情况下是宽松的,即使给定的日期格式可能与其配置为解析的格式不匹配,也不会抛出异常。您可以将其设置为不那么宽松,如下所示:

SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,它将检查字符在该日期是否实际有效。

  • 另请注意 [`parse(String source)`](https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-) 的 javadoc说*“该方法可能不会使用给定字符串的整个文本”*,因此您可能需要使用 [`parse(String source, ParsePosition pos)`](https://docs.oracle.com/javase/ 8/docs/api/java/text/DateFormat.html#parse-java.lang.String-java.text.ParsePosition-)重载,并验证字符串值是否与日期格式完全匹配,即所有文本被使用了。 (2认同)