问题
I need to get the day of the week from an NSDate
as a number.
For example, if today is Thursday I should get number 4, if Friday then number 5.
Does this functionality already exist?
回答1:
As per your requirement the following codes give you '4' for today i.e. Thursday 13 Dec 2012
NSMutableDictionary *weeks=[NSMutableDictionary new];
[weeks setObject:@"1" forKey:@"Monday"];
[weeks setObject:@"2" forKey:@"Tuesday"];
[weeks setObject:@"3" forKey:@"Wednesday"];
[weeks setObject:@"4" forKey:@"Thursday"];
[weeks setObject:@"5" forKey:@"Friday"];
[weeks setObject:@"6" forKey:@"Saturday"];
[weeks setObject:@"7" forKey:@"Sunday"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@",[weeks objectForKey:[dateFormatter stringFromDate:[NSDate date]]]);//gives you 4 for today i.e. Thursday 13 Dec 2012
OR
Little bit of tricky
NSCalendar *calender = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calender components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger dayCount = [dateComponents weekday]-1;
if (dayCount==0) {//as sunday will become 0, you need 7.
dayCount=7;
}
NSLog(@"Day count : %ld",dayCount);
回答2:
Use NSCalendar
like this:
NSCalendar *calObject = [NSCalendar currentCalendar];
NSDateComponents *comp = [calObject components:NSWeekdayCalendarUnit
fromDate:yourDateHere]; //provide date here
NSInteger day = [comp weekday]; //will return 1 = Sunday, 2 = Monday, etc.
回答3:
As sais in the doc: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html
Use:
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
Be carreful though, with this code, 1 is Sunday.
来源:https://stackoverflow.com/questions/13860373/geting-day-number-from-nsdate