使SimpleDateFormat.parse()在无效日期失败(例如,月份大于12) [英] Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)
问题描述
我正在使用 java.text.SimpleDateFormat
来解析表单yyyyMMdd
的字符串。 p>
如果我尝试解析一个月大于12的字符串,而不是失败,它会滚动到下一年。完全可运行的重复:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date
public class ParseDateTest {
public static void main(String [] args)throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd );
Date result = format.parse(20091504); //< - 不应该是有效的日期!
System.out.println(result); //打印Thu Mar 04 00:00:00 CST 2010
}
}
我宁愿有一个 ParseException
抛出。
有没有任何非哈基的方式来强制异常发生?。我的意思是,我不想手动检查这个月是否大于12.这很可笑。
感谢任何建议。
注意:我已经知道了Joda Time,但是我需要在没有外部库的普通JDK中完成。
你需要使它不宽容。因此,
format.setLenient(false);
应该这样做。
I'm using java.text.SimpleDateFormat
to parse strings of the form "yyyyMMdd"
.
If I try to parse a string with a month greater than 12, instead of failing, it rolls over to the next year. Full runnable repro:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParseDateTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date result = format.parse("20091504"); // <- should not be a valid date!
System.out.println(result); // prints Thu Mar 04 00:00:00 CST 2010
}
}
I would rather have a ParseException
thrown.
Is there any non-hacky way of forcing the exception to happen?. I mean, I don't want to manually check if the month is greater than 12. That's kind of ridiculous.
Thanks for any suggestion.
NOTE: I already know about Joda Time, but I need this done in plain JDK without external libraries.
You need to make it non-lenient. Thus,
format.setLenient(false);
should do it.
这篇关于使SimpleDateFormat.parse()在无效日期失败(例如,月份大于12)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!