How does Java “week year” really work?

后端 未结 2 1296
名媛妹妹
名媛妹妹 2020-11-28 13:47

This started as a simple error: I had YYYY instead of yyyy in my format string for a SimpleDateFormat object. But I\'m totally baffled

2条回答
  •  一向
    一向 (楼主)
    2020-11-28 13:56

    It's simple: December 27 2015 is day 1 of week 1 of week-year 2016 (and December 27 2026 is day 1 of week 1 of week-year 2027). This can be verified by adding these lines:

    SimpleDateFormat odf = new SimpleDateFormat("YYYY-ww-u");
    System.out.println(odf.format(d1));
    System.out.println(odf.format(d2));
    System.out.println(odf.format(d3));
    

    If a SimpleDateFormat outputs a date it can use all fields: year, month, day, day of week, week of month, week in year, week-year etc.

    On parsing, SimpleDateFormat expects a matching set of values: either day, month, year or day of week, week in year, week-year. Since you supplied a week-year but did not supply day of week and week in year, those to values have been assumed as 1.


    The actual values depend on your locale:

    • which week of a year is week 1
    • which day is the first day of the week

    (see https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#week_and_year)

    On my system (using de-ch locale, with "EEE MMM dd HH:mm:ss zzz yyyy - YYYY-ww-u" as format) I get

    Mo Jan 04 00:00:00 MEZ 2016 - 2016-01-1
    Mo Jan 04 00:00:00 MEZ 2016 - 2016-01-1
    Mo Jan 04 00:00:00 MEZ 2027 - 2027-01-1

提交回复
热议问题