我需要从NSDate
作为数字来获取星期几。
例如,如果今天是星期四,我应该得到4号,如果是星期五那么5号。
此功能是否已存在?
答案 0 :(得分:4)
像这样使用NSCalendar
:
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.
答案 1 :(得分:0)
使用:
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
小心思考,使用此代码,1是星期日。
答案 2 :(得分:-2)
根据您的要求,以下代码为您提供今天的'4',即2012年12月13日星期四
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
有点棘手
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);