这是 SimpleDateFormat 中的错误,还是功能?[复制]

Is this a bug in SimpleDateFormat, or a feature? [duplicate]

提问人:Jason 提问时间:7/29/2023 更新时间:8/8/2023 访问量:88

问:

我最近换了...continents 并暂时忘记以欧洲方式表示 2023 年 7 月 27 日,即 ,而是保留了美式文字,我立即将其作为参数传递给用欧洲模式初始化的实例的方法。我本来以为会出现,因为一年中只有 12 个月,但以下运行良好:"27/07/2023""07/27/2023"parseSimpleDateFormat"dd/MM/yyyy"ParseException

System.out.println(new SimpleDateFormat("dd/MM/yyyy").parse("07/27/2023"));

和输出

Fri Mar 07 00:00:00 EET 2025

我正在运行 JDK。corretto-17.0.2

我理解为什么这在数学上会发生(这是三月,耶!),我也理解它有自己的问题,例如线程(非)安全,但我想知道这是否是可以报告为错误的东西,或者背后是否有一些我不明白的逻辑。官方 Oracle 文档没有规定已弃用或考虑删除。感谢任何意见。27 = 2 * 12 + 32023 + 2 = 2025SimpleDateFormatSimpleDateFormat::parse()

java datetime 格式 simpledateformat

评论

3赞 Iłya Bursov 7/29/2023
来自 Java 文档 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).
2赞 Iłya Bursov 7/29/2023
See the parse(String, ParsePosition) method for more information on date parsing.
2赞 Iłya Bursov 7/29/2023
它并不缺少文档,第一个文档链接到 2nd,这意味着它基本上调用“扩展”版本(我假设只是将位置设置为 0)
2赞 Arvind Kumar Avinash 7/29/2023
Java-8 在 2014 年 3 月为您提供了现代日期时间 API。您仍在使用过时且容易出错的 API 的原因是什么?
1赞 Jason 8/6/2023
我完全理解,事实上,与此同时,我已经改用.DateTimeFormatter

答:

1赞 Jason 7/29/2023 #1

正如评论中提到的,如果你按照 to the (linked) 的文档进行操作,你会发现你可以调整解析的“宽大”,并且,如果你将其设置为严格,就像下面的代码一样,在这种情况下会抛出一个。parse(String)parse(String, ParsePosition)ParseException

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
System.out.println(sdf.parse("07/27/2023"));