NSDateComponents - day method returning wrong day

前端 未结 2 1072
无人及你
无人及你 2020-12-14 22:34

I can\'t seem to figure out why the day doesn\'t change when I get to the 6th of November, 2011. All I\'m doing is iterating through the days. Any help would be appreciated.

2条回答
  •  自闭症患者
    2020-12-14 22:56

    November, 6 is a day when time changed due to the Day Saving Time so that day actually lasts 25 hours and incorrect result is probably comes from that (in general adding time intervals to a date is unreliable because of calendar irregularities and bahaviour may depend on many parameters: current calendar, time zone, locale settings etc).

    The more correct way to iterate through days (per wwdc11 video "Performing Calendar Calculations"(iTunes link)) is to add appropriate number of date components to a starting date on each iteration:

    ...
    NSDateComponents *addComponents = [[NSDateComponents alloc] init];
    for (int i = 0; i < 7; i++) {
        [addComponents setDay: i];
        NSDate* d = [calendar dateByAddingComponents:addComponents toDate:date options:0];        
         NSDateComponents* dComponents = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:d];
    
         int day = [dComponents day];
         NSLog(@"\nDate: %@\nDay: %i", [d description], day);
    }
    

提交回复
热议问题