【问题标题】:Date parse exception when year is not four digits年份不是四位数时的日期解析异常
【发布时间】:2018-05-16 05:08:40
【问题描述】:

我在 Java 中有以下代码。

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

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

我希望这会导致解析异常,但我将一年解析为 0086,我相信这是过去的方式。我怎样才能使年份成为严格的 4 位数年份,其他任何事情都会例外。

【问题讨论】:

  • 我相信这是过去式。 - 你为什么这么认为?
  • 当你使用这个 SimpleDateFormat("MM/dd/yyyy");然后是 4 位数的年份,对于 2 位数,使用 SimpleDateFormat("MM/dd/yy");
  • 如果是 2 位数字或年份小于 4 位数字年份。我想要一个解析异常。
  • 您应该使用SimpleDateFormatter 的时间已经过去了。 :-) 那个类现在已经过时了,而且也是出了名的麻烦。而且我不知道有什么方法可以说服它按照你的意愿行事。无论如何,今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。见AxelH’s good answer

标签: java date datetime simpledateformat


【解决方案1】:

使用java.time 代替上一个日期API,您可以使用DateTimeFormatter,如果它不是正确的年份会抛出异常

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

线程“主”java.time.format.DateTimeParseException 中的异常:无法在索引 6 处解析文本“05/14/86”

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

1986-05-14

在相反的情况下,如果您希望同时允许 2 位和 4 位年份,您可以使用格式化程序的“可选”功能,使用 []。在可选块中提供uuuuuu 的可能格式,您将拥有:

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

2086-05-14

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

1986-05-14

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2020-09-18
    相关资源
    最近更新 更多