简体   繁体   中英

Given a year and a week number, how do you get the date of the first day of the week?

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?

-(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;
    }

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

[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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM