从服务器我收到 GMT 时间结构(用户定义的结构),使用我想将其转换为本地时间,我通过用接收到的结构填充 NSDatecomponent 来完成它,然后我使用日期格式化程序从中获取日期它,除了一种情况外,一切正常。如果 GMT 时间在 11 月 3 日之后(美国夏令时更改),则格式化程序会产生 1 小时的时差。
例如:如果预期时间是 11 月 3 日下午 4 点,则在从 GMT 转换为本地时间后,将给出 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_time 字符串比它应该的时间少一小时..
日志 :
strt_date_loc = 2013-11-30 06:56:00 +0000
sel_date_time = 2013 年 11 月 29 日晚上 10:56(但应该是晚上 11:56)
时区:帕洛阿尔托(美国)
本地到 GMT 转换:
- (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;
}
谢谢。