我需要这个以周为基础获取图表中的数据。这个对我不起作用。它返回的日期是所选年份的1月1日。有什么想法吗?
-(NSDate*) getFirstDateOfTheWeek:(NSString*) weekNr andYear: (NSString*) theYear {
int intYear = [theYear intValue];
int intWeek = [weekNr intValue];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
NSDateComponents * comp = [[NSDateComponents alloc] init];
[comp setYear:intYear];
[comp setWeek:intWeek];
NSDate *dateOfFirstDay = [gregorian dateFromComponents:comp];
NSDateComponents *dateComponents =
[gregorian components:NSWeekdayCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateOfFirstDay];
int year = [dateComponents year];
int month = [dateComponents month];
int day = [dateComponents day];
dateOfFirstDay= [gregorian dateFromComponents:dateComponents];
return dateOfFirstDay;
}
答案 0 :(得分:0)
除了setYear和setWeek之外,您还应该在NSDateComponents中设置Weekday。
[comp setWeekday:intWeek];
然后当抓取新组件时,你不需要很多标志,因为你真的只需要一天(以及其他用于调试):
[gregorian components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateOfFirstDay];