提问人:Jason 提问时间:7/29/2023 更新时间:8/8/2023 访问量:88
这是 SimpleDateFormat 中的错误,还是功能?[复制]
Is this a bug in SimpleDateFormat, or a feature? [duplicate]
问:
我最近换了...continents 并暂时忘记以欧洲方式表示 2023 年 7 月 27 日,即 ,而是保留了美式文字,我立即将其作为参数传递给用欧洲模式初始化的实例的方法。我本来以为会出现,因为一年中只有 12 个月,但以下运行良好:"27/07/2023"
"07/27/2023"
parse
SimpleDateFormat
"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 + 3
2023 + 2 = 2025
SimpleDateFormat
SimpleDateFormat::parse()
答:
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"));
评论
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).
See the parse(String, ParsePosition) method for more information on date parsing.
DateTimeFormatter