我如何通过 Foundation 获取星期几?

人气:251 发布:2022-10-16 标签: ios objective-c cocoa-touch nsdate

问题描述

How do I get the day of the week as a string?

解决方案

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];  
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

outputs current day of week as a string in locale dependent on current regional settings.

To get just a week day number you must use NSCalendar class:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];

753