如何计算仅包含周数和星期几的日期?
E.g。 2012年周二,第24周,周一开始。
答案 0 :(得分:1)
非常方便,NSCalendar将为您完成所有数学运算。首先,使用NSDateComponents设置参数:
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setWeek:24];
[comps setWeekday:3]; //map weekday names to numbers (e.g., Sunday is 1)
[comps setYear:2012];
然后使用这些日期组件创建公历日历:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
抓住你的NSDate:
NSDate *date = [gregorian dateFromComponents:comps];
答案 1 :(得分:0)
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:24];
[comp setDay:1];
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
[gregorian release]; // Clean up allocated objects by releasing them
[formatter release];
NSString * date = [NSString stringWithFormat:@"Week of %@", myDateString];