【问题标题】:Why does non-lenient SimpleDateFormat parse dates with letters in?为什么非宽松的 SimpleDateFormat 解析带有字母的日期?
【发布时间】:2013-02-13 10:04:33
【问题描述】:

当我运行以下代码时,我希望得到一个堆栈跟踪,但它看起来似乎忽略了我的 的错误部分,为什么会发生这种情况?

package test;

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

public class Test {
  public static void main(final String[] args) {
    final String format = "dd-MM-yyyy";
    final String value = "07-02-201f";
    Date date = null;
    final SimpleDateFormat df = new SimpleDateFormat(format);
    try {
      df.setLenient(false);
      date = df.parse(value.toString());
    } catch (final ParseException e) {
      e.printStackTrace();
    }
    System.out.println(df.format(date));
  }

}

输出是:

07-02-0201

【问题讨论】:

    标签: java simpledateformat


    【解决方案1】:

    DateFormat.parse(由 SimpleDateFormat 继承)的文档说:

    The method may not use the entire text of the given string.
    
    final String value = "07-02-201f";
    

    在您的情况下 (201f),它能够解析有效字符串直到 201,这就是为什么它没有给您任何错误。

    同一方法的“Throws”部分定义如下:

    ParseException - if the beginning of the specified string cannot be parsed
    

    因此,如果您尝试将字符串更改为

    final String value = "07-02-f201";
    

    你会得到解析异常,因为指定字符串的开头不能被解析。

    【讨论】:

      【解决方案2】:

      你可以查看整个字符串是否被解析如下。

        ParsePosition position = new ParsePosition(0);
        date = df.parse(value, position);
        if (position.getIndex() != value.length()) {
            throw new ParseException("Remainder not parsed: "
                    + value.substring(position.getIndex()));
        }
      

      此外,当parse 抛出异常时,position 也将产生getErrorIndex()

      【讨论】:

        【解决方案3】:

        已确认...我还发现 "07-02-201", "07-02-2012 is the date" 编译。但是,“bar07-02-2011”没有。

        从 SimpleDateFormat 中的代码看来,解析似乎在发现破坏匹配的非法字符时终止。但是,如果到目前为止已经解析的 String 是有效的,它就会被接受。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多