iphone - Strange NSDate and NSDateFormatter behaviour -
i trying date week of year. code , runtime value being calculated:

why year not correct? tried other formats well, y-w , gave me same results. issue fix if use yyyy-w wrong month/date since year calculated differently then. information yyyy:

now date 04-29 correct 1 week 18 in "yyyy" case (see here: http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php ) year correct when "yyyy" used (date wrong then).
so whats that?
-------- update 1 ---------
after adding solution offered in 1 of answers:

-------- update 2 ----------
so date 2000 same value "no year defined" (previously 1970). see here: http://openradar.appspot.com/12358210
-------- update 3 ----------
system information (for try replicating this).
xcode: version 4.6.2 (4h1003) ios: 6.1 osx: 10.8.3
-------- update 4 ----------
ios 5.1 provides different results when using this:

as if ios 5.1 not support "w" in nsdateformatter.
edit 1: answer doesn't explain results op seeing. see comments discussion more info
edit 2: peculiar results on machine. on ios 6, week doesn't respect first day of week setting in system preferences @ all:
ios 6 returns:
2000-1 -> 1st jan, 2000 (saturday)
2001-1 -> 6th jan, 2001 (saturday)
even if [calendar setfirstweekday: 3] , [dateformatter setcalendar: calendar], doesn't affect results @ (unlike ios 5)! bug in ios 6 nscalendar api. recommend using nsdatecomponents or calculating date yourself. should easy given info in answer - can assume iso-8601 (minimum 4 days in first week , week starts monday), unless of course, can ask user preference.
original answer
here's what's happening:
in locale, minimum number of days in week 5 , week starts on saturday.
assuming true, first week 5th jan (sat) - 11th jan 2013. , 18th week be, guessed it: 4th may 2013.
why? because apple follows unicode technical standard #35 version tr35-25 (on ios 6+).
f.4 week of year values calculated week of year field range 1 53 gregorian calendar (they may have different ranges other calendars). week 1 year first week contains @ least specified minimum number of days year. weeks between week 1 of 1 year , week 1 of following year numbered sequentially 2 52 or 53 (if needed). example, january 1, 1998 thursday. if first day of week monday , minimum days in week 4 (these values reflecting iso 8601 , many national standards), week 1 of 1998 starts on december 29, 1997, , ends on january 4, 1998. however, if first day of week sunday, week 1 of 1998 starts on january 4, 1998, , ends on january 10, 1998. first 3 days of 1998 part of week 53 of 1997. also, yyyy-w right format.
Comments
Post a Comment