[java 2019-12-16] SimpleDateFormat格式化跨年显示格式错误

使用SimpleDateFormat格式化时发现显示年份比实际年份多一年,这是因为yyyy和YYYY格式化时表示的含义是不同的,yyyy表示实际年份,YYYY表示Week year,Week year意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。

代码如下:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

    public static void main(String[] args) {

        String pattern1 = "yyyy-MM-dd";
        String pattern2 = "YYYY-MM-dd";
        Date date = new Date(119,11,30); //2019.12.30
        SimpleDateFormat sdf1 = new SimpleDateFormat(pattern1);
        SimpleDateFormat sdf2 = new SimpleDateFormat(pattern2);
        String date1 = sdf1.format(date);
        String date2 = sdf2.format(date);
        System.out.println("date1:"+pattern1+"	"+date1);
        System.out.println("date2:"+pattern2+"	"+date2);


    }
}

结果:

 觉得这个YYYY似乎没什么用,只有坑。。。

原文地址:https://www.cnblogs.com/shijt/p/12049034.html