In the IOS quiz app i had to code recently, i had a very specific requirement. I have to implement a system which had to retrieve data from parse.com based on a calendar week criteria. In other words, i had to perform a query that uses the year and week number to filter down the amount of data being retrieved.
To do so, i have to use NSDate to retrieve the date on the device itself and feed it into NSCalendar to determine the year and week of year. Part of the requirement was to start the week on a Monday instead of the default Sunday. To do that, i have to use calendar.firstWeekday = 2 which changes the start of week to a monday.
The app works fine until i tested it with the last week of the year which is 28th December 2015. This particular week is actually week number 53 of year 2015. However, i’m getting week number 1 of year 2015 instead! It was a mistake using year = datecomponent.year to determine the year.
The correct way of doing it should be to use
year = dateComponent.yearForWeekOfYear
This did solve the issue of the wrong year being reported. However, according to epoch converter, the first week of 2016 should be starting from on the 4th Jan 2016 instead of 28th Dec 2015. On the wikipedia of ISO 8601 week date , it says,
It is the first week with a majority (4 or more) of its days in January.
By including calendar.minimumDaysInFirstWeek = 4 , my app now works correctly in stating the first week of the year.
This is the code i have in my function which i hope will be useful to anyone working on a similar system of retrieving week numbers and year in their app.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
let calendar = NSCalendar.currentCalendar() //Sets the first week day to start on Monday instead calendar.firstWeekday = 2 //Sets the minimum number of days that must fall in the new year calendar.minimumDaysInFirstWeek = 4 let dateComponent = calendar.components([NSCalendarUnit.WeekOfYear, NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.YearForWeekOfYear], fromDate:NSDate()) weekNumber = dateComponent.weekOfYear year = dateComponent.yearForWeekOfYear |