在本周获取周数和星期一和星期日的日期(iOS上的Objective-C)

时间:2011-12-03 22:43:08

标签: objective-c nsdate nsdateformatter nsdatecomponents

如何才能获得本周的当前周数以及周一和周日的日期?

1 个答案:

答案 0 :(得分:13)

我不确定这是多么有效,因为它主要是从其他答案中拼凑出来的

快速浏览一下苹果文档

示例:

NSDate *today = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.firstWeekday = 2; // Sunday = 1, Saturday = 7

NSDateComponents *components = [gregorian components:NSWeekOfYearCalendarUnit fromDate:today];

NSUInteger weekOfYear = [components weekOfYear];

NSDate *mondaysDate = nil;
[gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&mondaysDate interval:NULL forDate:today];

NSLog(@"%ld %@", weekOfYear, mondaysDate);