Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: NSDate convert GMT to local time

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?

like image 910
dpigera Avatar asked Oct 10 '10 18:10

dpigera


3 Answers

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];
like image 138
Iñigo Beitia Avatar answered Nov 08 '22 22:11

Iñigo Beitia


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

NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:pubDate];
like image 25
nesimtunc Avatar answered Nov 08 '22 20:11

nesimtunc


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];
like image 37
JFK Avatar answered Nov 08 '22 20:11

JFK