我有几个字符串说"今晚8点"或者"今晚6点和#34;我需要找出如何将它们转换为NSDates。我需要格式为yyyy / mm / dd / hh。
更新
现在我回到了错误的一年。我今年的收入是9223372036854775807.
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Month, .Day, .Year], fromDate:NSDate())
let year = components.year
let month = components.month
let day = components.day
let NSDateString = "\(month)/\(day)/\(year) at \(date.chopPrefix(11))"
print(NSDateString)
答案 0 :(得分:3)
您不需要自己进行解析。有一个方便的NSDataDetector
类可以为您完成此任务:
let string = "Tonight at 7pm"
// Create an NSDataDetector that looks for dates
let detector = try! NSDataDetector(types: NSTextCheckingType.Date.rawValue)
// Create an array of all the possible matches
let matches = detector.matchesInString(string, options: [], range: NSMakeRange(0, string.utf16.count))
// Since you are only expecting one date, extract it.
if let date = matches.first?.date {
print("\(date)")
} else {
print("No matches found")
}
这会为您处理区域设置。例如 - 我在这里给出的结果日期为:
"2015-10-04 18:00:00 +0000"
这为您提供了一个很好的原始NSDate
实例,您可以根据需要存储或提供格式化的输出。
此外,这并不仅限于“今天”。将此代码放在游乐场中并尝试以下内容:
let string = "Wednesday at 7pm"
或
let string = "Yesterday at 7pm"
或
let string = "tomorrow morning at 2"
所有返回有效日期。
答案 1 :(得分:2)
我现在所做的工作如下:
let inputString = "Tonight at 6PM"
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: NSDate())
let dfm = NSDateFormatter()
dfm.dateFormat = "'Tonight at' hha"
let inputDate = dfm.dateFromString(inputString)!
let hour = calendar.components(.Hour, fromDate: inputDate).hour
let outputDate = calendar.dateFromComponents(components)?.dateByAddingTimeInterval(Double(hour * 60 * 60))
对外输出:
2015年10月4日,下午6:00
另一种方法是将今天的日期附加到输入字符串,然后再将它们全部解析。