Java 时间模式中 'yy' 和 'YY' 的区别

Difference between 'yy' and 'YY' in Java Time Pattern

来自文档 SimpleDateTimePatternyy 应该与 YY 相同。

今天是 Dec 30, 2019,现在我们得到 YY 今天是 20yy 今天是 19。 Java时间模式中的yyYY有什么区别?

你拥有它link:

y Year Year 1996; 96

Y Week year Year 2009; 09

周可以不同于当年

,例如新年的这一周

Week year定义为年的第一个星期四:

The first week of the year is the week that contains that year's first Thursday

yy是日历年,而YY是星期年。一周年可能不同于日历年,具体取决于一月一日是哪一天。例如参见 [​​=17=].

今天(2​​019年12月30日)就是一个很好的例子,日历年是2019年,但是周年是2020年,因为本周是2020年的第1周。所以yy将导致19,而 YY 结果为 20

一年中第一周的定义来自wikipedia page:

The ISO 8601 definition for week 01 is the week with the Gregorian year's first Thursday in it. The following definitions based on properties of this week are mutually equivalent, since the ISO week starts with Monday:

  • It is the first week with a majority (4 or more) of its days in January.
  • Its first day is the Monday nearest to 1 January.
  • It has 4 January in it. Hence the earliest possible first week extends from Monday 29 December (previous Gregorian year) to Sunday 4 January, the latest possible first week extends from Monday 4 January to Sunday 10 January.
  • It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.

If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, it is part of week 53 of the previous year. If it is on a Saturday, it is part of the last week of the previous year which is numbered 52 in a common year and 53 in a leap year. If it is on a Sunday, it is part of week 52 of the previous year.

一些地区,例如美国,不遵循 ISO-8601,因为他们使用星期日作为一周的第一天,但​​他们对周年有类似的规则。

They both represent a year but yyyy represents the calendar year while YYYY represents the year of the week.

一个例子比文字更能说明这一点。

package datetest;    

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

public class Test {

    public static void main(String[] args) {
        try {
            String[] dates = {"2018-12-01", "2018-12-31", "2019-01-01"};
            for (String date: dates) {
                SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
                Date d = dt.parse(date);

                SimpleDateFormat dtYYYY = new SimpleDateFormat("YYYY");
                SimpleDateFormat dtyyyy = new SimpleDateFormat("yyyy");

                System.out.println("For date :" + date + " the YYYY year is : " + dtYYYY.format(d) + " while for yyyy it's " + dtyyyy.format(d));
            }
        } catch (Exception e) {
            System.out.println("Failed with exception: " + e);
        }
    }
}

输出

For date : 2018-12-01 the YYYY year is : 2018 while for yyyy it's 2018
For date : 2018-12-31 the YYYY year is : 2019 while for yyyy it's 2018
For date : 2019-01-01 the YYYY year is : 2019 while for yyyy it's 2019