我希望这只是我正在经历的学习曲线。
我创建了一个任意日期。我想找到第三个星期五之后的星期六。
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]);
输出:
日期:2010-11-01 05:00:00 GMT
日期:2010-11-01 05:00:00 GMT
为什么呢?我该如何解决这个问题?
答案 0 :(得分:4)
// Sunday = 1, Saturday = 7
int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate: date] weekday];
答案 1 :(得分:2)
将组件更改为:
(NSWeekdayCalendarUnit | NSYearCalendarUnit)
击> <击> 撞击>
这有效:
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]);
希望这有帮助。