NSDateComponents components:fromDate and Time Zones

后端 未结 3 2074
抹茶落季
抹茶落季 2020-12-28 21:14

I have a method which extracts the hour and second components form a NSDate by breaking it down into its NSDateComponents. My code is as follows...

unsigned         


        
3条回答
  •  青春惊慌失措
    2020-12-28 21:40

    I agree with aqua. It is very misleading and has led me to days hitting my head against the screen. It works like this: [NSDate date] always returns current date. So in the example above it will be 2010-08-02 08:00:00. When we convert into NSDateComponents, the actual time is lost and converted into a set of integers (hour, year etc.) which no longer hold the Time Zone.

    When converting back to a NSDate object it will take the values of year, month, day etc. and give it to you relative to GMT, hence the hour lost. It's just the way it was decided in the framework. What I do is the following:

    +(NSDateComponents *)getComponentFromDate:(NSDate *)date {
    
        NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
        unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit;
        NSDateComponents* components = [gregorian components:unitFlags fromDate:date];
    
        NSTimeZone* timeZone = [NSTimeZone localTimeZone];
        if(timeZone.isDaylightSavingTime) components.hour = ((int)timeZone.daylightSavingTimeOffset/3600);
    
        [gregorian release];
    
        return components;
    }
    

    That will give me a 'corrected' version of the components rounded to the current day which when passed to the calendar to retrieve a date will always be set to 00:00:00 on the day of the date passed as argument.

提交回复
热议问题