先上代码:
String dateStr = "2021-10-29";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parse = dateFormat.parse(dateStr);
System.out.println(dateFormat.format(parse));
// 运行结果你猜是啥?还是抛异常?
再上结果:
20201031
不报错也就罢了,怎么还2020年呢?
之前一直顺手就这么使用SimpleDateFormat,没有出现问题,也没有深究,这次有个入参日期格式校验,结果掉坑了。。。
什么都先别说,直接查看API文档(有耐心的话看源码):
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.
See the parse(String, ParsePosition) method for more information on date parsing.
欲知详情,还得查看parse(String, ParsePosition),继续:
By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).
现在明朗了吧。
至于上面的为什么结果都已经差年了,有兴趣自己研究去吧。另外还得注意多线程环境下的使用问题。