为什么SimpleDateFormat.parse接受无效的日期字符串? [英] Why does SimpleDateFormat.parse accept an invalid date string?
本文介绍了为什么SimpleDateFormat.parse接受无效的日期字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个java代码,以特定格式输入日期。
I have a java code, that inputs date in a specific format.
static Date parseDate(String userInput){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(userInput);
System.out.println(date);
}catch(ParseException pe){
date=null;
System.out.println("Not a valid date");
}
return date;
}
现在我进入 2015-13-11 89:90:90
这是一个无效的日期。但是返回 Thu Jan 14 18:31:30 IST 2016
作为日期。为什么这样呢如何让它作为日期返回null?
Now I'm entering 2015-13-11 89:90:90
which is an invalid date. But it returns Thu Jan 14 18:31:30 IST 2016
as the date. Why is this so? How do I make it to return null as the date?
推荐答案
从一个 javadocs ,似乎使用宽松的解析方式,其中接受格式不正确的输入:
From a glance of the javadocs, it seems to be using a lenient
mode of parsing in which it accepts poorly formatted input:
添加此行
format.setLenient(false);
在您的DateFormat对象的初始化出现修复后。
after the initialization of your DateFormat object appears to fix it.
这篇关于为什么SimpleDateFormat.parse接受无效的日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文