SimpleDateFormat类不会为无效格式抛出异常
import java.text.ParseException;
public class Hello {
public static void main(String[] args) throws ParseException {
System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd").parse("23-06-2015"));
}
}
为什么这会返回Sun Dec 05 00:00:00 GMT 28
SimpleDateFormat的Javadoc有关于重复模式字母的说法:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it’s needed to separate two adjacent fields
因此,对于解析,“yyyy-MM-dd”相当于“y-M-d”.
使用此模式,“23-06-2015”被解析为年= 23,月= 6,dayOfMonth = 2015.
默认情况下,从0023年6月1日开始计算,并计算2015天后日期,将您带到0028年12月5日.
您可以使用SimpleDateFormat.setLenient(false)更改此行为 – 禁用lenalent时,它将为超出范围的数字引发异常.这在Calendar.setLenient()中有适当的记录
请注意,对于Java 8中的新代码,避免使用旧的Date和Calendar类是个好主意.如果可以,请使用LocalDateTime.parse(CharSequence文本,DateTimeFormatter格式化程序).