如何在Swift for iOS中使用NSDateFormatter格式化date?

我试图parsing这个date“2016年6月18日星期六”到“18/06/2016”我知道这可以使用正则expression式的方法,但我不知道如何得到一个输出使用。

在swift中使用NSDateFormatter的方法将是首选

干得好。

NSDateFormatter不支持具有顺序指标的日子,所以你必须摆脱它们。 你可以使用正则expression式:

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

那么你只需格式化date。

完整的代码:

  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) } 

请记住, NSNumberFormatter将根据当前的区域设置进行格式化。