gpt4 book ai didi

java - SimpleDateFormat 没有正确解析日期

转载 作者:行者123 更新时间:2023-12-03 20:38:18 27 4
gpt4 key购买 nike

我很困惑为什么 SimpleDateFormat 没有正确解析以下输入数据。

我试图在 String 上测试各种可能允许的日期格式,看看它是否可以使用其中一种格式正确解析。

注意:我使用的其他不正确的日期格式会报告解析错误。这就是我希望看到的。

我做错了什么?或者,我可以做些什么作为解决方法?

String dformat = "MM-dd-yyyy";
String cDate = "2013-12-28";
SimpleDateFormat f = new SimpleDateFormat(dformat);
Date dd = f.parse(cDate);

结果是成功的。解析的日期是:

Date Fri Sep 12 00:00:00 PST 195

嗯,日期应该是 2013 年 12 月 28 日。在这种情况下,我希望看到(就像我看到的其他无效格式一样):

java.text.ParseException: Unparseable date: "2013-12-28"

最佳答案

获取错误信息:

java.text.ParseException: Unparseable date: "2013-12-28"

您需要调用:

f.setLenient(false);

作为 parse(String source, ParsePosition pos) 的 javadoc说:

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

关于java - SimpleDateFormat 没有正确解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com