我正在尝试为我们的财务部门生成一些代码,他们需要一个字段来为他们提供一年中的当前周,但基于星期日作为一周的第一天。因此,例如 01-25-16 (MM-dd-yyyy) 将是第 4 周。但是,当我使用 java.util.Calendar
和 calendar.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);
}
这会返回周数 5,即使如果一周的开始时间是星期日,它应该是 4。
最佳答案
您必须更改 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()
isMONDAY
andgetMinimalDaysInFirstWeek()
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()
isSUNDAY
, 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
创建您的日历而不是更改某些属性,请参阅 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.
关于java - 使用java日历获取一年中的一周,星期日作为一周的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002981/