我从服务器获取 UTC 时区的字符串日期,我需要将其转换为本地时区。
MY CODE:
let utcTime = "2015-04-01T11:42:00.269Z"
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString(utcTime)
println("utc: \(utcTime), date: \(date)")
这打印 -
UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 11:42:00 +0000)
如果我删除
dateFormatter.timeZone = NSTimeZone(name: "UTC")
它打印
UTC: 2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 08:42:00 +0000)
我当地的时区是 UTC +3
在第一个选项中我得到 UTC
在第二个选项中我得到 UTC -3
我应该得到
UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 14:42:00 +0000)
那么如何将UTC日期格式转换为当地时间呢?
以下内容在 Objective-C 中对我有用:
// create dateFormatter with UTC time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string
// change to a readable time format and change to local time zone
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];
我保留这两个网站来方便地转换不同的时间格式:http://www.w3.org/TR/NOTE-datetime http://www.w3.org/TR/NOTE-datetime
http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/ http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
在 Swift 中它将是:
// create dateFormatter with UTC time format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create date from string
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.local
let timeStamp = dateFormatter.string(from: date!)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)