简体   繁体   English

年份不是四位数时的日期解析异常

[英]Date parse exception when year is not four digits

I have the following code in Java. 我在Java中有以下代码。

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String expiryDateInString = "05/14/86";

final Instant expiryDate = dateFormat.parse((expiryDateInString)).toInstant();

I want this to cause a parse exception but i am getting a year parsed as 0086, which i believe is way in the past. 我希望这会导致一个解析异常,但我得到一年解析为0086,我相信这是过去的方式。 How can i make the year to be a strictly 4 digit year and anything else will give an exception. 我怎样才能使这一年成为严格的4位数年份,其他任何事情都会例外。

Using java.time instead of the previous date API, you can use DateTimeFormatter that will throw an exception if it is not a correct year 使用java.time而不是之前的日期API,您可以使用DateTimeFormatter ,如果它不是正确的年份将抛出异常

DateTimeFormatter.ofPattern("MM/dd/uuuu").parse(("05/14/86")

Exception in thread "main" java.time.format.DateTimeParseException: Text '05/14/86' could not be parsed at index 6 线程“main”中的异常java.time.format.DateTimeParseException:无法在索引6处解析文本'05 / 14/86'

DateTimeFormatter.ofPattern("MM/dd/uuuu").parse(("05/14/1986")

1986-05-14 1986年5月14日

In the opposite case, if you want to allow both 2 and 4 digit year, you can use the "optional" feature of the formatter using [ and ] . 在相反的情况下,如果要同时允许2位和4位年份,可以使用[]使用格式化程序的“可选”功能。 Providing both possible format for the year uuuu and uu in optional blocks, you will have : 在可选块中提供年份uuuuuu可能格式,您将拥有:

DateTimeFormatter.ofPattern("MM/dd/[uuuu][uu]").parse(("05/14/86")

2086-05-14 2086年5月14日

DateTimeFormatter.ofPattern("MM/dd/[uuuu][uu]").parse(("05/14/1986")

1986-05-14 1986年5月14日

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM