Is this a Java DateFormat bug?

浪子不回头ぞ 提交于 2019-12-12 11:52:22

问题


The pattern is "dd-MM-yyyy"

I think the string "01-01-2010mwwwwwwwwwwwwwww" does not satisfy the pattern, but the following code shows the contrary.

Anyone can explain why?

public static void main(String[] args) throws Exception {

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

    Date date = df.parse("01-01-2010mwwwwwwwwwwwwwww");

    System.out.println(date);
}

Thanks


回答1:


The parse method does not try to match the entire input string. That is, the prefix 01-01-2010 matches, and that's enough.

From DateFormat.parse:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.


If you need to figure out if it was a "complete match", you could try the following:

SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

String strDate = "01-01-2010mwwwwwwwwwwwwwww";
ParsePosition pp = new ParsePosition(0);
Date date = df.parse(strDate, pp);
System.out.println("Complete match: " + (pp.getIndex() == strDate.length()));

strDate = "01-01-2010";
pp = new ParsePosition(0);
date = df.parse(strDate, pp);
System.out.println("Complete match: " + (pp.getIndex() == strDate.length()));

This prints

Complete match: false
Complete match: true



回答2:


It's because the default lenient parameter for DateFormat is true. This means the parser will parse input string even though it's in incorrect format. Which will (sometime) lead to incorrect result.

On the other hand, we can force the parser to be strict to given pattern. This means an incorrect input string will throw an exception.

public static void main(String[] args) throws Exception {
  SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
  df.setLenient(false); // Switch to strict mode
  Date date = df.parse("01-01-2010mwwwwwwwwwwwwwww"); // This will throw an exception
  System.out.println(date);
}


来源:https://stackoverflow.com/questions/3025942/is-this-a-java-dateformat-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!