无意发现一个dateformat的问题
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date eventDate = dateFormat.parse("2021-01-22 12:34:22"); System.out.println(dateFormat.format(eventDate));
//结果 : 20201130220212
2021年转换成2020年,没有抛出 ParseException 有点费解
看源码解释,默认是lenient的,如果一个格式错误,但是还能继续解析就返回成功,不抛出异常。如果设置成严格setLenient(false),就会抛出异常
* <p> 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 {@link #setLenient(boolean) setLenient(false)}.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); dateFormat.setLenient(false); Date eventDate = dateFormat.parse("2021-01-22 12:34:22"); System.out.println(dateFormat.format(eventDate));
//执行结果:
Exception in thread "main" java.text.ParseException: Unparseable date: "2021-01-22 12:34:22"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.idss.test.main(test.java:23)