Converting NSString to NSDate (and back again)

后端 未结 17 2494
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:26

How would I convert an NSString like \"01/02/10\" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDat

17条回答
  •  忘了有多久
    2020-11-22 00:18

    If anyone is interested in doing something like this in Swift these days, I have a start on something, although it's not perfect.

    func detectDate(dateString: NSString) -> NSDate {
    
        var error: NSError?
        let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)!
    
        if error == nil {
            var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length))
    
            let currentLocale = NSLocale.currentLocale()
            for match in matches {
                match.resultType == NSTextCheckingType.Date
                NSLog("Date: \(match.date.description)")
                return match.date
            }
        }
        return NSDate()
    }
    

提交回复
热议问题