WEEK_OF_YEAR inconsistent on different machines

前端 未结 2 1264
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 08:32

Update: ok, I seem to have found half the answer. If I created my Calendar with a no-argument getInstance, I get WEEK_OF_YEAR = 52. However, if I create it

2条回答
  •  甜味超标
    2020-12-21 09:01

    [See Update below. Incorrect answer.]

    For ISO 8601 weeks where week # 1 has the first Thursday, the correct answer 2010-W52.

    For comparison and experiment, try using either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time). And anyways, you should be using those as the java.util.Date and .Calendar classes are a notoriously troublesome mess.

    Joda-Time

    DateTime dateTime = new DateTime( 2011, 1, 1, 0, 0, 0, DateTimeZone.UTC );
    int weekNumber = dateTime.getWeekOfWeekYear();
    String output = ISODateTimeFormat.weekDate().print( dateTime );
    

    UPDATE: Answer Irrelevant

    I assumed incorrectly that java.util.Calendar determined week-of-year by the ISO 8601 standard. It does not. It uses a Locale to influence the result of its getFirstDayOfWeek() method. It then uses the earliest seven day period beginning with that day as its first week of year. See "First Week" section of doc.

    So using Joda-Time or java.time will not help in debugging the problem. I leave this answer to highlight (a) the difference between using a standard week versus a localized week, and (b) the importance of not making assumptions.

提交回复
热议问题