1

从服务器我收到 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;
}

谢谢。

4

1 回答 1

2

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

夏令时在该日期无效,因此 UTC/GMT 与加利福尼亚时间之间的差异为 8 小时。所以

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

这就是你得到的。

添加:您将本地日期转换为 GMT 组件无法正常工作,因为

[[NSTimeZone defaultTimeZone] secondsFromGMT] 

是与 GMT 的当前时差,而不是在要转换的日期有效的时差。以下应该可以正常工作(甚至更短):

NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *date_comp = [cal components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:localDate];
于 2013-10-30T08:10:23.793 回答