Month: June 2015
Sketch #127 – Stormy Cloud
Tutorial – Get the day of the week with NSCalendar for any NSDate
NSCalendar is a mighty class which let you do a lot of different things with NSDate. At first it might look a bit complicated but with some time it gets very useful when working with dates (especially with NSDateFormatter). As language I will use Objective-C but translating it to Swift shouldn’t be too hard.
So if you want to know which day of a week a particular NSDate is you have to create a NSCalendar to work with. To do all the date related stuff you also need a NSDateComponents object where you define how to work with the calendar. With them we create dates for a particular week in were our date is and loop through them. In every iteration we check if the created date is the same as our original date. I’ve created a function for date comparisons since I need them regularly often in my app. You basically just compare the single components like day, month, year, hour, minute,…
//Create our NSCalendar to work with NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; //Week starts on Monday in Europe! People in the US can comment the following line out. [gregorian setFirstWeekday:2]; //get today NSDate* today = [NSDate date]; //We need the dateComponents to do work with our NSCalendar NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday ) fromDate:today]; // Loop through week for (int i = 2; i < 9; i++) { //Set the weekday and create a new date from it [dateComponents setWeekday:i]; NSDate *weekDay = [gregorian dateFromComponents:dateComponents]; //Compare the new date with our "today" if ([DateFunctions isDate:weekDay equalWith:today]) { //Do your stuff here, day of the week is i } }
So with this little piece of code you are able to determine which day of the week your NSDate object is. I hope this will be helpful for you, if you have any questions feel free to use the comments below!