Since, in IPhone development, we can’t use descriptionWithCalendarFormat function to extract different components from NSDate object, there is another way to do that: NSCalendar. If you’re reading this post only for the weekday, so here goes one liner for you (don’t forget that weekday 1 = sunday, not monday like some of us may think):
int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:dateFromString] weekday];
NSCalendar is very useful if you wish to use your elements of date apart from each other. Here is more detailed example how to separate them:
// just some date NSDate *fooDate = [NSDate date]; // setting units we would like to use in future unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit; // creating NSCalendar object NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // extracting components from date NSDateComponents *components = [calendar components:units fromDate:fooDate]; // getting our fooDate components. On at the time. Oh, and they're integers! [components year]; [components month]; [components day]; [components weekday];
List of all available units:
NSEraCalendarUnit, NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit, NSHourCalendarUnit, NSMinuteCalendarUnit, NSSecondCalendarUnit, NSWeekCalendarUnit, NSWeekdayCalendarUnit, NSWeekdayOrdinalCalendarUnit, NSQuarterCalendarUnit
Tags: iphone-dev, NSCalendar, NSDate, NSDateComponents
Thanks for the one liner – was pulling my hair out how to find the weekday of the first day in any given month!