Подтвердить что ты не робот

Изменить NSDate из одного часового пояса в другой

Учитывая дату в NSString, как "2012-12-17 04:36:25" (это GMT), как можно просто изменить ее на другие часовые пояса, такие как EST, CST

Все шаги, которые я видел до сих пор, заняли много ненужных шагов

4b9b3361

Ответ 1

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)