我需要从一个数字中获取星期几NSDate
。
例如,如果今天是星期四,我应该得到 4 号,如果是星期五,那么我应该得到 5 号。
此功能是否已经存在?
我需要从一个数字中获取星期几NSDate
。
例如,如果今天是星期四,我应该得到 4 号,如果是星期五,那么我应该得到 5 号。
此功能是否已经存在?
像这样使用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.
采用:
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
不过要小心,使用此代码,1 是星期日。
根据您的要求,以下代码今天为您提供“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
或者
有点棘手
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);