arm1.ru

Getting the Weekday Number in Objective-C

Cheat sheet for getting the weekday number from NSDate:

/* get the Gregorian calendar */
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
/* NSDateComponents lets you get the weekday number, day of month, etc. from NSDate. */
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
// get the weekday number. It will be from 1 to 7
NSInteger weekday = [comps weekday];

In iOS, depending on which region is selected in the device settings, the week starts either on Monday, as in Russia, or on Sunday, as in the US. If you only need to output the short name of the weekday, for example: Mon, Tue, Wed, Thu, you can do it like this:

NSDateFormatter *weekdayDateFormatter = [[NSDateFormatter alloc] init];
[weekdayDateFormatter setDateFormat: @"EE"];
NSLog(@"%@", [weekdayDateFormatter stringFromDate:dateFromString]);
keyboard_return