NSDate - Convert Date to GMT

后端 未结 6 919
故里飘歌
故里飘歌 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:38

    Working with time in Cocoa can be complicated. When you get an NSDate object, it's in the local time zone. [[NSTimeZone defaultTimeZone] secondsFromGMT] gives you the offset of the current time zone from GMT. Then you can do this:

    NSDate *localDate = // get the date
    NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
    

    Now gmtDate should have the correct date in GMT for you. In order to display it, look at NSDateFormatter, specifically the setDateStyle and setTimeStyle methods. You create an NSDateFormatter, configure it the way you want, and then call stringFromDate: to get a nicely formatted string.

提交回复
热议问题