[英]NSDate from string is always nil
I receive dates as String
like this one: 我收到像String
这样的日期:
"2016-05-20T12:25:00.0" “2016-05-20T12:25:00.0”
I want to get its corresponding NSDate
object, and I'm trying this way: 我想获取其对应的NSDate
对象,并且正在尝试这种方式:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)
where dateStr
is like the example I wrote first. 其中dateStr
就像我首先编写的示例。 I took the dateFormat
string from this page , but I get a nil
date, what is wrong there? 我从此页面上获取了dateFormat
字符串,但得到的日期为nil
,那是什么问题呢?
Thanks in advance 提前致谢
You have a few problems with your date format. 您的日期格式有一些问题。 First Y
is for weekOfYear, D
is for day of year. 第一个Y
代表weekOfYear, D
代表一年中的一天。 hh
is used for 12 hours format, decimal second you should use capital S
and you need to escape the 'T'
hh
用于12小时格式,十进制秒应使用大写S
并且需要转义'T'
You should do as follow: 您应该执行以下操作:
let dateString = "2016-05-20T12:25:00.0"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.dateFromString(dateString) {
print(dateFormatter.stringFromDate(date) ) // "2016-05-20T12:25:00.0\n"
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
print(dateFormatter.stringFromDate(date) )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.