我需要从NSDate
中获取星期几作为数字。
例如,如果今天是星期四,我应该得到数字4,如果星期五是5。
该功能已经存在吗?
最佳答案
根据您的要求,以下代码在今天即2012年12月13日星期四为您提供“ 4”
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
要么
有点棘手
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);