使用Swift 2将String转换为NSDate [英] Convert String to NSDate with Swift 2
本文介绍了使用Swift 2将String转换为NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字符串转换为 NSDate
这是我的代码
I'm trying to convert a string to NSDate
here is my code
let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
print ( dateFormatter.dateFromString( strDate ) )
我一直得到 nil
推荐答案
T 格式字符串需要单引号,因此不会被视为符号:
The "T" in the format string needs to be single quoted so it will not be consider a symbol:
Swift 3.0
Swift 3.0
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")
输出:
日期:2015-11-01 00 :00:00 +0000
date: 2015-11-01 00:00:00 +0000
Swift 2.x
Swift 2.x
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")
输出:
日期:2015-11-01 00:00:00 +0000
date: 2015-11-01 00:00:00 +0000
这包括如果ASCII字母用于表示文字文本,则需要将ASCII字母括在单引号中。
This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.
这篇关于使用Swift 2将String转换为NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文