问题
I passed %%#@-01-01
as date format, but got no exception. Why?
SimpleDateFormat df = null;
df = new SimpleDateFormat("%%#@-01-01");
回答1:
Quoting the javadoc for SimpleDateFormat:
[...] unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.
The format string %%#@-01-01
contains no letters, but there's no requirements that there must be at least one letter.
Proof that it works (well, "works" is a relative concept here, given that it's pretty useless):
SimpleDateFormat fmt = new SimpleDateFormat("%%#@-01-01");
Date date = fmt.parse("%%#@-01-01");
System.out.println(date);
System.out.println(fmt.format(date));
try {
fmt.parse("9999-01-01");
} catch (Exception e) {
System.out.println(e);
}
Output
Thu Jan 01 00:00:00 EST 1970
%%#@-01-01
java.text.ParseException: Unparseable date: "9999-01-01"
回答2:
The pattern you have provided (%%#@-01-01
) is not invalid. Only letters need to be quoted, all other symbols are simply copied into the format string. From the docs (emphasis mine):
Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.
来源:https://stackoverflow.com/questions/32391406/simpledateformat-not-giving-illegalargumentexception-on-passing-invalid-date-f