如何快速转换包括时区的日期? [英] How can I convert including timezone date in swift?
本文介绍了如何快速转换包括时区的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将2015-08-14T20:02:25-04:00
转换为2015-08-14 16:02
我在下面尝试过,但执行效果不佳(返回nil).
I want to convert 2015-08-14T20:02:25-04:00
to 2015-08-14 16:02
I tried below, but it could't execute well(returned nil).
let d = "2015-08-14T20:02:25-04:00"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
let date: NSDate? = formatter.dateFromString(d)
如何转换此日期格式?
推荐答案
Xcode 8•Swift 3
您需要转义'T'并使用适当的时区符号.请注意,这取决于您的日期字符串是否表示UTC(距格林尼治标准时间为零秒)时区,时区为Z "XXXXX"
或不带+00:00 "xxxxx"
:
You need to escape 'T' and use the appropriate timezone symbol. Note that it will depend if your date string represents a UTC (zero seconds from GMT) time timezone with Z "XXXXX"
or without it +00:00 "xxxxx"
:
let dateString = "2015-08-14T20:02:25-04:00"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
if let date = formatter.date(from: dateString) {
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let string = formatter.string(from: date)
print(string)
}
如果您需要一些参考,可以使用:
If you need some reference you can use this:
这篇关于如何快速转换包括时区的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文