格林尼治标准时间到本地时间转换夏时制改变

从服务器我收到格林尼治标准时间结构(用户定义的结构),使用,我想将其转换为本地时间,我已经完成填充NSDatecomponent收到的结构,然后我已经使用dateformatter获取date它,除了一个案件,一切正常。 如果GMT时间在11月3日(美国夏令时改变)之后格式化器产生1小时时差。

例如:如果预计时间是11月3日下午4点,格林尼治标准时间从格林威治标准时间转换到当地时间为11月3日下午3点。

任何想法如何避免它。

编辑:

// Selected Dates NSDateComponents *sel_date = [[NSDateComponents alloc]init]; sel_date.second = sch_detail.sel_dates.seconds; sel_date.minute = sch_detail.sel_dates.mins; sel_date.hour = sch_detail.sel_dates.hours; sel_date.day = sch_detail.sel_dates.date; sel_date.month = sch_detail.sel_dates.month; sel_date.year = sch_detail.sel_dates.year; sel_date.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; // Get the Date format. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; // Start_date formatter. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMM dd, yyyy hh:mm a"]; [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; NSDate *strt_date_loc = [gregorian dateFromComponents:sel_date]; // Get date string. NSString *sel_date_time = [dateFormatter stringFromDate: strt_date_loc];+ 

sel_date_timestring是比它应该是less一小时..

日志:

strt_date_loc = 2013-11-30 06:56:00 +0000

sel_date_time = Nov 29,2013 10:56 PM(但应该是下午11:56)

时区:帕洛阿尔托(美国)

本地转换:

 - (NSDateComponents*) convert_to_gmt_time : (NSDate*) date { NSDate *localDate = date; NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset; NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval]; NSDateComponents *date_comp = [[NSCalendar currentCalendar] components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:gmtDate]; return date_comp; } 

感谢名单。

你的结果是正确的。 date格式化程序不使用当地时间和GMT之间的当前时间差,而是使用转换date有效的时间差。

夏令时在当天不生效,所以UTC / GMT和加州时间的差值为8小时。 因此

 2013-11-30 06:56:00 +0000 = 2013-11-29 22:56:00 -0800 = Nov 29, 2013 10:56 PM 

这就是你得到的。

ADDED:您将本地date转换为GMT组件不能正常工作,因为

 [[NSTimeZone defaultTimeZone] secondsFromGMT] 

是GMT的当前时差,而不是在转换date有效的时差。 以下应该可以正常工作(甚至稍微短一点):

 NSCalendar *cal = [NSCalendar currentCalendar]; [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; NSDateComponents *date_comp = [cal components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:localDate];