当前位置: 移动技术网 > IT编程>开发语言>Java > Java中日期格式化YYYY-DD的操作bug

Java中日期格式化YYYY-DD的操作bug

2020年03月09日  | 移动技术网IT编程  | 我要评论

写这篇博文是记录下跨年的bug。去年隔壁组的小伙伴就是计算两个日期之间间隔的天数,因为跨年的原因计算有误。

当时测试组的小姐姐也没有模拟出来这种场景,导致上生产环境直接影响线上的数据。

今天逛技术论论坛正好遇到java日期的操作bug。

1 yyyy 和 yyyy

别看字,看代码

@test
 public void testweekbasedyear() {
 calendar calendar = calendar.getinstance();
 // 2019-12-31
 calendar.set(2019, calendar.december, 31);
 date strdate1 = calendar.gettime();
 // 2020-01-01
 calendar.set(2020, calendar.january, 1);
 date strdate2 = calendar.gettime();
 // 大写 yyyy
 simpledateformat formatyyyy = new simpledateformat("yyyy/mm/dd");
 system.out.println("2019-12-31 转 yyyy/mm/dd 格式: " + formatyyyy.format(strdate1));
 system.out.println("2020-01-01 转 yyyy/mm/dd 格式: " + formatyyyy.format(strdate2));
 // 小写 yyyy
 simpledateformat formatyyyy = new simpledateformat("yyyy/mm/dd");
 system.out.println("2019-12-31 转 yyyy/mm/dd 格式: " + formatyyyy.format(strdate1));
 system.out.println("2020-01-01 转 yyyy/mm/dd 格式: " + formatyyyy.format(strdate2));
 }

输出结果

2019-12-31 转 yyyy/mm/dd 格式: 2020/12/31
2020-01-01 转 yyyy/mm/dd 格式: 2020/01/01
2019-12-31 转 yyyy/mm/dd 格式: 2019/12/31
2020-01-01 转 yyyy/mm/dd 格式: 2020/01/01

细心的同学应该发现了2019-12-31用yyyy/mm/dd
此刻变成了2020/12/31

??为何呢?yyyy这么大的能耐,能跑到2020年代去?

我2019年底买的东西,你如果用yyyy来格式化出库日期,我是不是得到2020年底才能收到货? 此bug问题挺大的呀!

yyyy 到底是何方妖怪?👺

java's datetimeformatter pattern "yyyy" gives you the week-based-year, (by default, iso-8601 standard) the year of the thursday of that week.

例子:

下面就是用yyyy格式化代码

12/29/2019 将会格式化到2019年 这一周还属于2019年
12/30/2019 将会格式化到2020年 这一周已经属于2020年

看字说话yyyy,week-based year 是 iso 8601 规定的。

2019-12-31号这一天,安周算年份已经属于2020年了,格式化之后就变成2020年,后面的月份日期不变。

2 dd 和 dd

 private static void tryit(int y, int m, int d, string pat) {
 datetimeformatter fmt = datetimeformatter.ofpattern(pat);
 localdate  dat = localdate.of(y,m,d);
 string  str = fmt.format(dat);
 system.out.printf("y=%04d m=%02d d=%02d " +
  "formatted with " +
  "\"%s\" -> %s\n",y,m,d,pat,str);
 }
 public static void main(string[] args){
 tryit(2020,01,20,"mm/dd/yyyy");
 tryit(2020,01,21,"dd/mm/yyyy");
 tryit(2020,01,22,"yyyy-mm-dd");
 tryit(2020,03,17,"mm/dd/yyyy");
 tryit(2020,03,18,"dd/mm/yyyy");
 tryit(2020,03,19,"yyyy-mm-dd");
 }

输出结果

y=2020 m=01 d=20 formatted with "mm/dd/yyyy" -> 01/20/2020
y=2020 m=01 d=21 formatted with "dd/mm/yyyy" -> 21/01/2020
y=2020 m=01 d=22 formatted with "yyyy-mm-dd" -> 2020-01-22
y=2020 m=03 d=17 formatted with "mm/dd/yyyy" -> 03/77/2020
y=2020 m=03 d=18 formatted with "dd/mm/yyyy" -> 78/03/2020
y=2020 m=03 d=19 formatted with "yyyy-mm-dd" -> 2020-03-79

看到没有?最后的3个日期都错误了。这里的大写的dd代表的是处于这一年中那一天,不是处于这个月的那一天,但是dd就没有问题。

小伙伴们一定要记住了不要犯类似的错误。 此锅我们不背。

结论

yyyy和yyyy不一样的,dd和dd也是不一样要切记。

以上所述是小编给大家介绍的java中日期格式化yyyy-dd的操作bug,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网