使用以下过于复杂的代码,几乎可以从字符串中提取日期:
let dateStringArray:[String] = ["29-01-2017 10:41:18:825325012","29-01-2017 10:41:18:894631028"]
let formatString = "dd-MM-yyyy HH:mm:ss:nnnnnnnnn"
let dayRange = formatString.range(of: "dd")
let monthRange = formatString.range(of: "MM")
let yearRange = formatString.range(of: "yyyy")
let hourRange = formatString.range(of: "HH")
let minuteRange = formatString.range(of: "mm")
let secondRange = formatString.range(of: "ss")
let nanoRange = formatString.range(of:"nnnnnnnnn")
let dateString = dateStringArray[0]
let dateComponents = DateComponents( year:Int(dateString.substring(with: yearRange!)),
month:Int(dateString.substring(with: monthRange!)),
day:Int(dateString.substring(with: dayRange!)),
hour:Int(dateString.substring(with: hourRange!)),
minute:Int(dateString.substring(with: minuteRange!)),
second:Int(dateString.substring(with: secondRange!)),
nanosecond:Int(dateString.substring(with: nanoRange!)))
let nano = Int(dateString.substring(with: nanoRange!))
let currentCalendar = Calendar.current
let dateExtracted = currentCalendar.date(from: dateComponents)
print("\(dateExtracted!)")
最终印刷品的输出为:“2017-01-29 10:41:18 +0000 \ n”
这有问题(1)必须有一个更简单的方法。 (2)&更重要的是,为什么纳秒组件显然没有出现?
答案 0 :(得分:1)
(1)必须有一个更简单的方法
使用日期格式化程序:
let dateString = "29-01-2017 10:41:18:825325012"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss:SSSSSSSS"
let dateExtracted = dateFormatter.date(from: dateString)!
(2)为什么纳秒组分显然没有出现?
description
的{{1}}方法不显示小数秒,但是
你可以用
Date
结果可能与原始纳秒值略有不同
由于舍入错误而在字符串中,因为currentCalendar.component(.nanosecond, from: dateExtracted!)
在内部存储
浮点数(自参考日期以来的秒数)
2001年1月1日)。如果您使用上面建议的日期格式化程序
分辨率限制为毫秒(比较NSDateFormatter milliseconds bug)。