当前位置:网站首页>A tragedy triggered by "yyyy MM DD" and vigilance before New Year's Day~

A tragedy triggered by "yyyy MM DD" and vigilance before New Year's Day~

2022-06-26 06:02:00 Interview with Java factory

Preface

When the new year's Day holiday comes , I'm just going out for a few days , However, some App When , I found one that should be caused by the carelessness of the front end bug, stay 2019.12.30 set out , result App It shows 2020.12.30( I was so scared that I thought my order was wrong , Is it time to drag the programmers to heaven ).

In view of the possibility that some programmers may be dragged to heaven , And I used to learn Java I have paid attention to this problem since I was born , So I'd like to put this question to you , I hope we can try our best to avoid carelessness in this regard ( After all, this kind of problem is difficult to detect ).

Text


public class DateTest {
    
    public static void main(String[] args) {
    
        Calendar calendar = Calendar.getInstance();
        calendar.set(2019, Calendar.AUGUST, 31);
        Date strDate = calendar.getTime();
        DateFormat formatUpperCase = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("2019-08-31 to yyyy-MM-dd: " + formatUpperCase.format(strDate));
        formatUpperCase = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println("2019-08-31 to YYYY/MM/dd: " + formatUpperCase.format(strDate));
    }
}

Let's take a look at the results :

2019-08-31 to yyyy-MM-dd: 2019-08-31
2019-08-31 to YYYY/MM/dd: 2019-08-31

If we change the date to 12.31:

2019-12-31 to yyyy-MM-dd: 2019-12-31
2019-12-31 to YYYY-MM-dd: 2020-12-31

The problem arises , Although it is a small detail , But the user will be confused after reading it , But we as developers , Can't be ignorant , Check the document quickly :
 Insert picture description here

y:year-of-era; A serious year , After new year's day ;Y:week-based-year; As long as this week crosses the new year , So this week is the next year ; For example, this year (2019-2020) 12.31 This week is a new year's week , and 12.31 It's Tuesday , That use YYYY It will show 2020, Use yyyy Will follow 1.1 Just started to be 2020.

Although this is a small knowledge point , But many people fell into the pit , You can record it after learning , If you think it's good, you can also like it and pay attention to it . Here, I wish you all a great help in coding , Never bug~

原网站

版权声明
本文为[Interview with Java factory]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180502200165.html