关于 swift:如何从”今晚 7 点”中获取 NSDate?

How can I get an NSDate out of "Tonight at 7PM"?

本问题已经有最佳答案,请猛点这里访问。

我有几个字符串显示"今晚 8 点"或"今晚 6 点",我需要找出如何将它们转换为 NSDates。我需要格式为 yyyy/mm/dd/hh。

更新:

现在我返回了错误的年份。我一年收到 9223372036854775807。

1
2
3
4
5
6
7
8
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)


您不需要自己进行解析。有方便的 NSDataDetector 类为您执行此操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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")
}

这会为您处理语言环境。例如 - 我在哪里给出了结果日期:

1
"2015-10-04 18:00:00 +0000"

这为您提供了一个不错的原始 NSDate 实例,您可以根据需要存储或提供格式化输出。

此外,这不会将您与"今天"联系起来。将此代码放在操场上并尝试以下操作:

1
let string ="Wednesday at 7pm"

1
let string ="Yesterday at 7pm"

1
let string ="tomorrow morning at 2"

它们都返回有效日期。


我现在的工作如下:

1
2
3
4
5
6
7
8
9
10
11
12
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))

输出:

Oct 4, 2015, 6:00 PM

另一种方法是将今天的日期附加到输入字符串,然后再次将它们一起解析。