NSDate - Convert Date to GMT

后端 未结 6 896
故里飘歌
故里飘歌 2020-11-28 02:45

I need the ability to convert an NSDate value to a GMT Date.

How can I go about converting an NSDate value to a GMT formatted NSDate<

6条回答
  •  春和景丽
    2020-11-28 03:22

    While Alex's answer was a good start, it didn't deal with DST (daylight savings time) and added an unnecessary conversion to/from the reference date. The following works for me:

    To convert from a localDate to GMT, taking DST into account:

    NSDate *localDate = <>
    NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
    NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset]; // NOTE the "-" sign!
    

    To convert from a GMT date to a localDate, taking DST into account:

    NSDate *gmtDate  = <>
    NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];
    NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];
    

    One small note: I used dateByAddingTimeInterval, which is iOS 4 only. If you are on OS 3 or earlier, use addTimerInterval.

提交回复
热议问题