开发者

NSDate get a specific day of the week?

I hope this is just a learning curve I'm going through.

I create an arbitrary date. I want to find the Saturday following the third Friday.

    NSLog(@"Date: %@", [date description]);
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"EST"];
    [calendar setTimeZone:zone];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
    [components setWeekday:6];        // 1 = Sunday ... 7 = Saturday
    [components setWeekdayOrdinal:3]; // 3rd Friday
    resultDate = [calendar dateFromComponents:components];
    NSLog(@"Date: %@", [resultDate description]);

And the output:

Dat开发者_运维百科e: 2010-11-01 05:00:00 GMT

Date: 2010-11-01 05:00:00 GMT

Why? How can I fix this?


// Sunday = 1, Saturday = 7

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


Change the components to:

(NSWeekdayCalendarUnit | NSYearCalendarUnit)

This works:

 NSDate *today = [[NSDate alloc] init];
 NSLog([today description]);

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

 NSDateComponents *weekdayComponents = [gregorian components:(NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:today];

 NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
 [componentsToSubtract setDay: 0 - ([weekdayComponents weekday])];
 [componentsToSubtract setWeekdayOrdinal:([weekdayComponents weekday] <= 6) ? 3 : 4];
 //[componentsToSubtract setWeekdayOrdinal:3]; //old way - not perfect

 NSDate *saturday = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0]; 
 NSDateComponents *components =
 [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
     fromDate: saturday];
 saturday = [gregorian dateFromComponents:components];

 NSLog([saturday description]);

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜