ios - 将 NSDate 从一个时区更改为另一个时区

标签 ios objective-c swift nsdate nsdateformatter

<分区>

给定 NSString 中的日期,如“2012-12-17 04:36:25”(格林威治标准时间),如何简单地将其更改为其他时区,如 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)

编辑:添加 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)

关于ios - 将 NSDate 从一个时区更改为另一个时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917938/

相关文章:

ios - 如何以编程方式在 iOS 上创建和拨号 VPN 连接?

objective-c - 带绑定(bind)的可编辑 NSTableView 不会在模型中设置值

ios - 如何将目标操作转换为阻止?

ios - 如何从 navigationController viewControllers 中删除特殊 Controller ?

ios - 我可以将 Xcode 4 中的 Utilities 面板设置为在所有新项目中默认打开吗?

swift - 在 Plist 中检索用户定义的值

swift - 当用户输入地理围栏半径时将当前位置保存到 plist

xcode - swift a func 在仍在执行时返回 nil

ios - 是否可以同时更新我的​​应用程序的版本和价格变化

objective-c - IBOutlets 属性。放不放