在 iOS 中将本地时间转换为 EST

Convert Local Time To EST in iOS

请建议如何将本地时间转换为美国东部时间。 我用谷歌搜索了但没有得到任何相关的答案。

我们将不胜感激。

NSString *str = @"2012-12-17 04:36:25";
NSDateFormatter* gmtDf = [[[NSDateFormatter alloc] init] autorelease];
[gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[gmtDf setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
 NSDate* gmtDate = [gmtDf dateFromString:str];
NSLog(@"%@",gmtDate);

NSDateFormatter* estDf = [[[NSDateFormatter alloc] init] autorelease];
[estDf setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[estDf setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *estDate = [estDf dateFromString:[gmtDf stringFromDate:gmtDate]]; // you can also use str
NSLog(@"%@",estDate);
-(NSString * )convertTimeZoneFromDateString:(NSString *)string
{
 NSDateFormatter * format = [[NSDateFormatter alloc] init];

// from server dateFormat
[format setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss '+0000'"];

// get date from server
NSDate * dateTemp = [format dateFromString:string];

// new date format
[format setDateFormat:@"MMM dd, hh:mm a"];

// convert Timezone
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];

NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:dateTemp];

NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:dateTemp];

NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

// get final date in LocalTimeZone
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:dateTemp];

// convert to String
NSString *dateStr = [format stringFromDate:destinationDate];

return dateStr;
}

Swift 2.0:

let todayDateString: String = "2016-12-17 06:36:25"
let gmtDateformat: NSDateFormatter = NSDateFormatter()

gmtDateformat.timeZone = NSTimeZone(name: "GMT")
gmtDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let gmtDate: NSDate = gmtDateformat.dateFromString(todayDateString)!
let estDateformat: NSDateFormatter = NSDateFormatter()
estDateformat.timeZone = NSTimeZone(name: "EST")
estDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let estDate: NSDate = estDateformat.dateFromString(gmtDateformat.stringFromDate(gmtDate))!

print("EST Time \(estDate)")