GMT到本地时间转换,夏令时变化

时间:2013-10-30 06:35:13

标签: ios nsdate nsdateformatter nstimezone

从服务器I接收GMT时间结构(用户定义的结构),使用我想将其转换为本地时间,我已经通过填充NSDatecomponent接收到的结构来完成它,然后我使用了日期formattter从它获取日期,一切正常,除了一个案例。如果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)

TimeZone:Palo Alto(美国)

本地到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;
}

感谢名单。

1 个答案:

答案 0 :(得分:2)

你的结果是对的。日期格式化程序不使用当前时差 在您当地时间和格林威治标准时间之间,但是在时间差异是有效的 转换的日期。

夏令时在该日期无效, 所以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];
相关问题