将NSDate从一个时区转换到另一个时区

16

如何将一个以GMT格式表示的NSString日期字符串(例如"2012-12-17 04:36:25")简单地转换到其他时区(例如EST、CST)?

到目前为止,我看到的所有步骤都太冗长了。


为什么这些步骤是不必要的? - vikingosegundo
可能是重复问题:https://dev59.com/k3I-5IYBdhLWcg3wbHq- - Ramy Al Zuhouri
1个回答

29
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);

编辑:添加 Swift 代码

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)

编辑:添加 Swift 3 代码

    let str: String = "2012-12-17 04:36:25"
    let gmtDf = DateFormatter()
    gmtDf.timeZone = TimeZone(identifier: "GMT")
    gmtDf.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let gmtDate = gmtDf.date(from: str)!
    print(gmtDate)

    let estDf = DateFormatter()
    estDf.timeZone = TimeZone(identifier: "EST")
    estDf.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let estDate = estDf.date(from: gmtDf.string(from: gmtDate))!
    print(estDate)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接