GMT to Local Time Conversion with Daylight Saving Time change

前端 未结 1 1672
慢半拍i
慢半拍i 2021-01-16 04:51

From server I\'m receiving GMT time structure(user defined structure), using that I want to convert it into local time, I have done it by filling the NSDatecomponent with th

相关标签:
1条回答
  • 2021-01-16 05:25

    Your result is correct. The date formatter does not use the current time difference between your local time and GMT, but the time difference that is in effect at the date that is converted.

    The daylight savings time is not in effect at that date, so the difference between UTC/GMT and California time is 8 hours. Therefore

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

    and that is what you got.

    ADDED: Your conversion of the local date to GMT components does not work correctly because

    [[NSTimeZone defaultTimeZone] secondsFromGMT] 
    

    is the current time difference to GMT, and not the time difference that is in effect at the date to be converted. The following should work correctly (as is even slightly shorter):

    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDateComponents *date_comp = [cal components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:localDate];
    
    0 讨论(0)
提交回复
热议问题