views:

1583

answers:

3

Hi,

I'm trying to figure out what day (i.e. Monday, Friday...) of any given date (i.e. Jun 27th, 2009)

Thank you.

+3  A: 

Use NSCalendar and NSDateComponents. As shown in the NSDateComponents documentation:

NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
Chuck
Where is "comps" coming from? Also, technically @ThisThib is correct that -weekday returns an NSInteger value. Shouldn't be a problem for any calendar I know, but in the name of correctness and portability... ;-)
Quinn Taylor
+4  A: 

Hi

You may have a look to the NSDate and NSCalendar classes. For example, here and here

They provide the following code:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
ThibThib
+2  A: 

I've been doing:

NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[theDateFormatter setDateFormat:@"EEEE"];
NSString *weekDay =  [theDateFormatter stringFromDate:[NSDate date]];

This has the added bonus of letting you choose how you'd like the weekday to be returned (by changing the date format string in the setDateFormat: call

Lots more information at:

http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369

Jeff Hellman