gpt4 book ai didi

java - java.text.SimpleDateFormat 中的奇怪行为期望 yyyyMMdd 给定 yyyy-MM-dd

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:00 24 4
gpt4 key购买 nike

我在使用 SimpleDateFormat 将字符串解析为日期时遇到了一个非常奇怪的行为。考虑以下单元测试:

@Test
public void testParse() throws ParseException
{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

String dateStr = "2012-12-21";
Date parsedDate = dateFormat.parse(dateStr);
Calendar date = Calendar.getInstance();
date.setTime(parsedDate);

Assert.assertEquals(2012, date.get(Calendar.YEAR));
Assert.assertEquals(11, date.get(Calendar.MONTH)); // yeah, Calendar sucks
Assert.assertEquals(21, date.get(Calendar.DAY_OF_MONTH));
}

可以看出,上面的代码中存在一个故意的错误:SimpleDateFormat 是用"yyyyMMdd" 初始化的,但是字符串要解析的格式为 "yyyy-MM-dd"。我希望这样的事情会导致 ParseException,或者至少在尽力而为的基础上正确 进行解析。相反,由于某些奇怪的原因,日期被解析为 2011-11-02。嗯?!

这是 Not Acceptable ,因为处理输入时的一个错误会导致完全出乎意料/毁灭性的结果。同时切换到 JodaTime,但如果能了解那里出了什么问题就好了。

最佳答案

摘自 JavaDoc for setLenient :

public void setLenient(boolean lenient)

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.
With strict parsing, inputs must match this object's format.

如果你将它设置为false,你会得到ParseException

关于java - java.text.SimpleDateFormat 中的奇怪行为期望 yyyyMMdd 给定 yyyy-MM-dd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859211/

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