如何使用Swift从包含时间戳的字符串中提取日期?
例如:
当以字符串格式给出以下timeStamp时,需要哪些步骤来提取日期并将其转换为字符串?
如果timeStamp = "3/5/2015 7:12:17 PM"
然后期望的结果将是= "3/5/2015"
答案 0 :(得分:1)
let input = "3/5/2015 7:12:17 PM"
let output = "3/5/2015"
extension NSDate {
var formatted: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "M/d/yyyy"
return formatter.stringFromDate(self)
}
}
extension String {
var asNSDate:NSDate {
let styler = NSDateFormatter()
styler.dateFormat = "M/d/yyyy h:mm:ss a"
return styler.dateFromString(self) ?? NSDate()
}
}
println( input.asNSDate.formatted ) // "3/5/2015"