iPhone: NSDate convert GMT to local time

25,863

Solution 1

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];

Solution 2

This code will convert the GMT time to the device's local time.

NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:pubDate];

Solution 3

NSDate *sourceDate = [NSDate dateWithTimeIntervalSince1970:gmtTimestamp];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [destinationTimeZone secondsFromGMTForDate:0];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
[dateFormatter setTimeZone:destinationTimeZone];
NSString *localTimeString = [dateFormatter stringFromDate:destinationDate];
Share:
25,863
dpigera
Author by

dpigera

EmberJS, NodeJS, Objective-C engineer

Updated on July 10, 2020

Comments

  • dpigera
    dpigera almost 4 years

    I currently have an API call returning me a date/time in the format: 2010-10-10T07:54:01.878926

    Can I assume this is GMT? I also converted this to an NSDate object. Is there a way to use the local iPhone time to recalculate the time?

  • Paul Armstrong
    Paul Armstrong over 11 years
    The message -(NSString *)dateWithCalendarFormat:timezone: does not exist in Apple's documentation.
  • willhblackburn
    willhblackburn over 9 years
    How does this convert GMT to local time? I believe it's doing the opposite and converting local to GMT right?
  • Husam
    Husam about 8 years
    Swift : let localDate = NSDate(timeInterval: NSTimeInterval(NSTimeZone.systemTimeZone().secondsFromGMT), sinceDate: date)
  • Юрий Сталоверов
    Юрий Сталоверов over 3 years
    Good example, but it converting from Local Time to GTM.