如何使用Cocoa查找任何给定日期的星期几

时间:2009-06-29 09:15:02

标签: objective-c cocoa nsdate nscalendar nsdatecomponents

我想知道任何特定日期(即2009年6月27日)的哪一天(即星期一,星期五......)

谢谢。

4 个答案:

答案 0 :(得分:28)

我一直在做:

NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[theDateFormatter setDateFormat:@"EEEE"];
NSString *weekDay =  [theDateFormatter stringFromDate:[NSDate date]];

这有额外的好处,让你选择如何返回工作日(通过更改setDateFormat中的日期格式字符串:call

有关更多信息,请访问:

http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369

答案 1 :(得分:16)

您可以查看NSDate和NSCalendar类。 例如,herehere

他们提供以下代码:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

答案 2 :(得分:6)

使用NSCalendar和NSDateComponents。如NSDateComponents文档中所示:

NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];

答案 3 :(得分:-1)

这就是我最终完成的工作,它完全符合预期。它需要一个日期,将日期更改为该月的第一天,并获得该日期的

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSDateComponents *monthDateComponents = [[NSCalendar currentCalendar] components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |
                                         NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate: date];

//  build date as start of month
monthDateComponents.year = components.year;
monthDateComponents.month = components.month;
monthDateComponents.day = 1;

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    [gregorian setFirstWeekday:1];

NSDate *builtDate =[gregorian dateFromComponents: monthDateComponents];
//    NSDateComponents *weekdayComponents =[gregorian components: NSCalendarUnitWeekday fromDate: builtDate];

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"E"];

NSString *firstDay = [df stringFromDate:builtDate];
if([firstDay isEqual:@"Sun"])  //  do for the other 6 days as appropriate
    return 7;