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!
Thank you very much for the 1 liner!!!!! I have been going round and round in circles!
hii, well thanks for the one-liner….but I am still in problem, I have an application, in which I am getting different weekday returned from different server date; though the day remains the same. For example : if the server returns time of US, the weekday is 6th, but if the server returns the time of HongKong, the weekday changes to 7th, though when this check was made both US and Hongkong are on the same day(i.e. 6th) …..what could be the problem dear..??