3

时间格式字符串 - 年底的惊喜

 2 years ago
source link: https://blog.victorchu.info/posts/6fee69fb/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

时间格式字符串 - 年底的惊喜

发表于

2021-12-30 更新于 2022-02-08 分类于 FAQJDK

Waline: 0 阅读次数: 5 本文字数: 778 阅读时长 ≈ 1 分钟

时间格式字符串 - 年底的惊喜

这一个常在元旦附近出没的 Bug,主要原因是 Java 日期格式 FormatString 中的 yyyy 被写成了 YYYY。
要注意的是,对于年份来说,大写的 Y 和小写的 y 其意义是不同的。y 是 Year, Y 表示的是 Week year

经过试验,得出的结果如下:Week year 意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。

注意上面的 Week year 指 format 时的结果,对于 YYYY 格式使用 parse, 会得到意想不到的结果。

SimpleDateFormat upperFormater = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
SimpleDateFormat lowerFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(lowerFormater.parse("2021-12-30 09:00:00"));
String lower = lowerFormater.format(lowerFormater.parse("2021-12-30 09:00:00"));
System.out.println(lower);
String upper = upperFormater.format(lowerFormater.parse("2021-12-30 09:00:00"));
System.out.println(upper);
System.out.println(upperFormater.parse("2021-12-30 09:00:00"));
坚持分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK