How to format the date using NSDateFormatter in Swift for iOS?

二次信任 提交于 2019-12-13 10:14:08

问题


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.



来源:https://stackoverflow.com/questions/37733659/how-to-format-the-date-using-nsdateformatter-in-swift-for-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!