【发布时间】:2013-11-09 14:56:13
【问题描述】:
我从服务器接收 GMT 时间结构(用户定义的结构),使用我想将其转换为本地时间,我通过用接收到的结构填充 NSDatecomponent 来完成它,然后我使用日期格式化程序来从中获取日期,除一种情况外,一切正常。如果 GMT 时间在 11 月 3 日之后(Daylight Saving Time 美国更改),格式化程序将产生 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;
}
谢谢。
【问题讨论】:
-
显示您的相关代码并显示一些示例数据。包括相关值的实际日志输出。
-
请稍等
-
记录
strt_date_loc和sel_date_time。粘贴实际的日志输出。你在哪个时区? -
@maddy 请检查编辑
标签: ios nsdate nsdateformatter nstimezone