Calendar Weeks in Swift

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.

 

Hello world!

Hello! Thanks for coming to my blog!

I had been thinking about starting a blog for a very long time but due to work/life/laziness and tons of other excuses, i had delayed it until now.

Why now, some of you might asked. Well, it seems like an appropriate time since i have just “finished” coding my first IOS app and there seems to be quite a lot of design and coding issues that i wished to document down for both my reference and for others who might have encountered the same issues as i had.

Feel free to leave me a comment if you spot any mistakes in my code or if you have a better solution! :]