0

我需要从一个数字中获取星期几NSDate

例如,如果今天是星期四,我应该得到 4 号,如果是星期五,那么我应该得到 5 号。

此功能是否已经存在?

4

3 回答 3

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.
于 2012-12-13T13:09:20.783 回答
0

正如文档中所说:https ://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html

采用:

NSCalendar * calendar = [NSCalendar  currentCalendar];
[calendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];

不过要小心,使用此代码,1 是星期日。

于 2012-12-13T13:09:04.393 回答
-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

或者

有点棘手

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);
于 2012-12-13T13:12:30.550 回答