问题
I can only find algorithm for getting ISO 8601 week (week starts on a Monday).
However, the iCal spec says
A week is defined as a seven day period, starting on the day of the week defined to be the week start (see WKST). Week number one of the calendar year is the first week that contains at least four (4) days in that calendar year.
Therefore, it is more complex than ISO 8601 since the start of week can be any day of the week.
Is there an algorithm to determine what is the week number of a date, with a custom start day of week?
or... is there a function in iCal4j that does this? Determine a weekno from a date?
Thanks!
p.s. Limitation: I'm using a JVM language that cannot extend a Java class, but I can invoke Java methods or instantiate Java classes.
回答1:
if (input_date < firstDateOfTheYear(WKST, year))
{
return ((isLeapYear(year-1))?53:52);
}
else
{
return ((dayOfYear(input_date) - firstDateOfTheYear(WKST, year).day)/7 + 1);
}
firstDateOfTheYear returns the first calendar date given a start of week(WKST) and the year, e.g. if WKST = Thursday, year = 2012, then it returns Jan 5th.
dayOfYear returns sequencial numerical day of the year, e.g. Feb 1st = 32
Example #1: Jan 18th, 2012, start of week is Monday
- dayOfYear(Jan 18th, 2012) = 18
- firstDateOfTheYear(Monday, 2012) = Jan 2nd, 2012
(18 - 2)/7 + 1 = 3 Answer Week no. 3
Example #2: Jan 18th, 2012, start of week is Thursday
- dayOfYear(Jan 18th, 2012) = 18
- firstDateOfTheYear(Thursday, 2012) = Jan 5th, 2012
(18 - 5)/7 + 1 = 2 Answer Week no. 2
Example #3: Jan 1st, 2012, start of week is Monday
- firstDateOfTheYear(Monday, 2012) = Jan 2nd, 2012
- IsLeapYear(2012-1) = false
Jan 1st, 2012 < Jan 2nd, 2012 Answer Week no. 52
回答2:
Let
daysInFirstWeek
be the number of days on the first week of the year that are in January. Week starts on aWKST
day. (e.g. if Jan 1st is aWKST
day, return 7)Set
dayOfYear
to the n-th days of the input date's year (e.g. Feb 1st = 32)If
dayOfYear
is less than or equal todaysInFirstWeek
3.1. if
daysInFirstWeek
is greater than or equal to 4,weekNo
is 1, skip to step 5.3.2. Let
daysInFirstWeekOfLastYear
be the number of days on the first week of the previous year that are in January. Week starts on aWKST
day.3.3. if
daysInFirstWeekOfLastYear
is 4 or last year is Leap year anddaysInFirstWeekOfLastYear
is 5,weekNo
is 53, otherwiseweekNo
is 52, skip to step 5.Set
weekNo
toceiling((dayOfYear - daysInFirstWeek) / 7)
4.1. if
daysInFirstWeek
greater than or equal to 4, incrementweekNo
by 14.2. if
daysInFirstWeek
equal 53 and count of days on the first week (starting fromWKST
) of January in the year ofinputDate
's year + 1 is greater than or equal to 4, setweekNo
to 1return
weekNo
来源:https://stackoverflow.com/questions/8999892/algorithm-for-calculating-a-week-from-a-date-with-custom-start-of-week-for-i