给定一年和一周的数字,您如何获得一周中第一天的日期?

时间:2022-05-10 20:19:48

I need this for getting data in a graph for week basis. This one does not work for me. The date that it returns is first of January of the selected year. Any ideea?

我需要这个以周为基础获取图表中的数据。这个对我不起作用。它返回的日期是所选年份的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;
    }

1 个解决方案

#1


0  

You should setWeekday in your NSDateComponents in addition you setYear and setWeek.

除了setYear和setWeek之外,您还应该在NSDateComponents中设置Weekday。

[comp setWeekday:intWeek];

Then when grabbing the new components you don't need many of the flags, as you really only need the day (and the others for debugging):

然后在抓取新组件时,您不需要许多标志,因为您实际上只需要一天(以及其他用于调试):

    [gregorian components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateOfFirstDay];

#1


0  

You should setWeekday in your NSDateComponents in addition you setYear and setWeek.

除了setYear和setWeek之外,您还应该在NSDateComponents中设置Weekday。

[comp setWeekday:intWeek];

Then when grabbing the new components you don't need many of the flags, as you really only need the day (and the others for debugging):

然后在抓取新组件时,您不需要许多标志,因为您实际上只需要一天(以及其他用于调试):

    [gregorian components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateOfFirstDay];