ios 如何快速转换包括时区日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32022906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert including timezone date in swift?
提问by naohide_a
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).
我想转换2015-08-14T20:02:25-04:00
为2015-08-14 16:02
我在下面尝试过,但它无法很好地执行(返回 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)
How can I convert this date format?
如何转换此日期格式?
回答by Leo Dabus
Xcode 8 ? Swift 3
Xcode 8 ? 斯威夫特 3
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"
:
您需要转义 'T' 并使用适当的时区符号。请注意,这取决于您的日期字符串是否表示带有 Z"XXXXX"
或不带 Z 的 UTC(格林威治标准时间零秒)时区+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:
如果你需要一些参考,你可以使用这个:
回答by Joffrey Outtier
You can use :
您可以使用 :
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
Hope this help you !
希望这对你有帮助!