java 使 SimpleDateFormat.parse() 在无效日期上失败(例如,月份大于 12)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1905551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)
提问by Sergio Acosta
I'm using java.text.SimpleDateFormatto parse strings of the form "yyyyMMdd".
我java.text.SimpleDateFormat用来解析表单的字符串"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:
如果我尝试解析一个大于 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"); // <- should not be a valid date!
System.out.println(result); // prints Thu Mar 04 00:00:00 CST 2010
}
}
I would rather have a ParseExceptionthrown.
我宁愿有一个ParseException抛出。
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.
有没有强制异常发生的非hacky方式?我的意思是,我不想手动检查月份是否大于 12。这有点荒谬。
Thanks for any suggestion.
感谢您的任何建议。
NOTE: I already know about Joda Time, but I need this done in plain JDK without external libraries.
注意:我已经知道 Joda Time,但我需要在没有外部库的普通 JDK 中完成。
回答by BalusC
回答by Ortomala Lokni
You can use the Java 8 time API. If by example you use a month with a value of 15:
您可以使用 Java 8 时间 API。例如,如果您使用值为 的月份15:
String strDate = "20091504";
TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyyMMdd").parse(strDate);
You will directly have an exception
你会直接有异常
Exception in thread "main" java.time.format.DateTimeParseException:
Text '20091504' could not be parsed:
Invalid value for MonthOfYear (valid values 1 - 12): 15
回答by Arvind Katte
By using Java 8 LocalDateyou can write like this,
通过使用 Java 8,LocalDate你可以这样写,
String strDate = "20091504";
LocalDate date1 = LocalDate.parse(strDate, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(date1);
Here is the Exception is thrown during parsing
这是解析过程中抛出的异常
Exception in thread "main" java.time.format.DateTimeParseException: Text '20091504' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 15
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at com.katte.infa.DateFormatDemo.main(DateFormatDemo.java:22)
Caused by: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 15
at java.time.temporal.ValueRange.checkValidIntValue(Unknown Source)
at java.time.temporal.ChronoField.checkValidIntValue(Unknown Source)
at java.time.chrono.IsoChronology.resolveYMD(Unknown Source)
at java.time.chrono.IsoChronology.resolveYMD(Unknown Source)
at java.time.chrono.AbstractChronology.resolveDate(Unknown Source)
at java.time.chrono.IsoChronology.resolveDate(Unknown Source)
at java.time.chrono.IsoChronology.resolveDate(Unknown Source)
at java.time.format.Parsed.resolveDateFields(Unknown Source)
at java.time.format.Parsed.resolveFields(Unknown Source)
at java.time.format.Parsed.resolve(Unknown Source)
at java.time.format.DateTimeParseContext.toResolved(Unknown Source)
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
... 3 more

