Objective C – Convert local time into GMT time.

These days m working on iPhone development and came across an interesting problem of converting GMT time into local time. After some research, I found this interesting function achieve it:


-(NSString *)convertGMTDateFromLocalDate:(NSString *)gmtDateStr
{
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@”yyyy-MM-dd HH:mm”];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@”GMT”];

[formatter setTimeZone:gmt];

NSDate *localDate = [formatter dateFromString:gmtDate]; // get the date

NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method

NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] – timeZoneOffset;

NSDate *gmtCurrentDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

return [formatter stringFromDate:gmtCurrentDate];
}


Leave a Reply

Your email address will not be published. Required fields are marked *