简体   繁体   中英

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

I'm trying to generate some code for our financial department, and they require a field that will give them the current week of the year, but based off of Sunday being the first day of the week. So for instance 01-25-16 (MM-dd-yyyy) would be week 4. However when I try it using java.util.Calendar and calendar.setFirstDayOfWeek to Sunday, it tells me that this is week 5 because it seems to be counting from the end of December to the 3rd of January as week 1.

Here is the code I've written so far:

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);
}

This returns a week number of 5, even though it should be 4 if basing the start of the week on Sunday.

You have to change minimalDaysInFirstWeek , see 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.

See also 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.

But if you code for your financial department , you should rather create your calendar with the right 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.

The definition of week of year is locale dependent. See this related question for more information. Why dec 31 2010 returns 1 as week of year? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM