本文介绍了将NSDate从一个时区更改为另一个时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 NSString
中给出日期,例如2012-12-17 04:36:25(也就是GMT),如何将其更改为其他时区EST,CST
Given a date in NSString
like "2012-12-17 04:36:25" (which is GMT) how one can simply change it to other time zones like EST, CST
到目前为止我看到的所有步骤都采取了许多不必要的步骤
All the steps I saw so far took so many unnecessary steps
推荐答案
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代码
Edit : Adding swift code
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代码
Adding Swift 3 code
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)
这篇关于将NSDate从一个时区更改为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!