SimpleDateFormat小坑

本文揭示了在使用Java SimpleDateFormat解析日期时遇到的年份错误,重点讲解了默认的宽容解析行为和如何设置严格模式。通过实例展示了代码和API文档解析过程,警示开发者注意多线程环境和格式一致性。

 

先上代码:

String dateStr = "2021-10-29";

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parse = dateFormat.parse(dateStr);
System.out.println(dateFormat.format(parse));
        
// 运行结果你猜是啥?还是抛异常?

再上结果:

20201031

不报错也就罢了,怎么还2020年呢?

之前一直顺手就这么使用SimpleDateFormat,没有出现问题,也没有深究,这次有个入参日期格式校验,结果掉坑了。。。

什么都先别说,直接查看API文档(有耐心的话看源码):

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

See the parse(String, ParsePosition) method for more information on date parsing.

欲知详情,还得查看parse(String, ParsePosition),继续:

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).

现在明朗了吧。

至于上面的为什么结果都已经差年了,有兴趣自己研究去吧。另外还得注意多线程环境下的使用问题。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsdhla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值