java - SimpleDateFormat 没有正确解析日期

标签 java date simpledateformat date-parsing

我很困惑为什么 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/

相关文章:

java - Java 中的 SimpleDateFormat 和 Locale API

java - SimpleDateFormat 警告 要获取本地格式,请使用 getDateInstance()、getDateTimeInstance() 或 getTimeInstance(),

java - 线程 "main"java.util.NoSuchElementException 中出现异常,无法从控制台获取输入整数

java - ZoneId ID 的本地化名称

java - 更新-错误消息: "Cannot switch on a value of type String[]. Only convertible int values, Strings or enum variables are permitted"

php - 当日期为 UNIX 时间戳格式时,如何按日期对记录进行分组?

java - 使用 DecimalFormat 的问题

java - Java Swing 的日期选择器 GUI 组件

date - BigQuery - DATE_TRUNC 错误

java - 是否可以在 Java 中用冒号格式化 UTC 时区?