How to format the date using NSDateFormatter in Sw

2019-09-22 11:21发布

问题:

I am trying to parse this date "18th of June 2016. Saturday" to "18/06/2016" I'm aware this can be done using the regex method but I'm not sure how you'd get an output using that.

A method using NSDateFormatter in swift would be preferred

回答1:

Here you go.

NSDateFormatter does not support days with ordinal indicators, so you have to get rid of them. You can use regex:

    let regex = try NSRegularExpression(pattern: "[st|nd|rd|th]", options: NSRegularExpressionOptions())
    regex.replaceMatchesInString(dateString, options: NSMatchingOptions(), range: NSMakeRange(0, 4), withTemplate: "")

then you simply format the date.


Complete code:

    let dateString = NSMutableString(string: "18th of June 2016. Saturday")

    do {
        let regex = try NSRegularExpression(pattern: "[st|nd|rd|th]", options: NSRegularExpressionOptions())
        regex.replaceMatchesInString(dateString, options: NSMatchingOptions(), range: NSMakeRange(0, 4), withTemplate: "")

        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        formatter.dateFormat = "d' of 'MMMM y'.' EEEE"
        let date = formatter.dateFromString(dateString as String)
        formatter.dateStyle = .ShortStyle
        formatter.locale = NSLocale.currentLocale()
        let output = formatter.stringFromDate(date!)
        print(output)

    } catch let error as NSError { print(error) }


Keep in mind that NSNumberFormatter will format according to the current locale settings.