使用 java 日历获取一年中的第几周,星期日作为一周的第一天

Get the week of year, with sunday as the first day of the week using java calendar

我正在尝试为我们的财务部门生成一些代码,他们需要一个字段来为他们提供一年中的当前周,但基于星期日作为一周的第一天。因此,例如 01-25-16 (MM-dd-yyyy) 将是第 4 周。但是当我尝试使用 java.util.Calendarcalendar.setFirstDayOfWeek 到星期日时,它告诉我这是第 5 周,因为它似乎是从 12 月底到 1 月 3 日算作第 1 周。

这是我到目前为止编写的代码:

private static int getWeekOfYearBySunday(DateTime dt){
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(dt.getMillis());
    calendar.setFirstDayOfWeek(Calendar.SUNDAY);

    return calendar.get(Calendar.WEEK_OF_YEAR);
}

这 returns 周数为 5,即使如果将一周的开始时间定在星期日,它应该是 4。

一年中第几周的定义取决于区域设置。有关更多信息,请参阅此相关问题。 Why dec 31 2010 returns 1 as week of year?.

您必须更改 minimalDaysInFirstWeek,请参阅 Calendar#setMinimalDaysInFirstWeek(int)

Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1. If it must be a full week, use value 7.

另见 GregorianCalendar:

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

但是,如果您为 财务部门 编写代码,则应该使用正确的 Locale instead of changing some properties, see Calendar#getInstance(Locale):

创建日历

Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale.