在NSString中有一个像“2012-12-17 04:36:25”(即GMT)的日期,可以简单地将其更改为其他时区,如EST,CST
我目前看到的所有步骤都采取了许多不必要的步骤
解决方法
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);
let str: String = "2012-12-17 04:36:25" let gmtDf: NSDateFormatter = NSDateFormatter() gmtDf.timeZone = NSTimeZone(name: "GMT") gmtDf.dateFormat = "yyyy-MM-dd HH:mm:ss" let gmtDate: NSDate = gmtDf.dateFromString(str)! print(gmtDate) let estDf: NSDateFormatter = NSDateFormatter() estDf.timeZone = NSTimeZone(name: "EST") estDf.dateFormat = "yyyy-MM-dd HH:mm:ss" let estDate: NSDate = estDf.dateFromString(gmtDf.stringFromDate(gmtDate))! print(estDate)