2016-06-09 42 views
-8

我想解析这个日期“2016年6月18日。星期六”到“18/06/2016” 我知道这可以使用正则表达式方法完成,但我不知道如何得到一个使用它的输出。如何在Swift for iOS中使用NSDateFormatter格式化日期?

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

+1

使用NSDateFormatter是适当的解决方案。使用正则表达式根本不是你应该怎么做的。用迄今为止尝试过的方法更新你的问题。 – rmaddy

+1

也许阅读文档。 – Alexander

+0

“NSDateFormatter”的Apple文档:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/。如果你对'NSDateFormatter'有特定的问题,那么编辑你的问题来包含代码和你遇到的问题。 –

回答

0

在这里你去。

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

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

那么你只需格式化日期。


完整代码:

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将根据当前区域设置格式化。

+0

由于原始日期字符串采用特定语言(英语),因此您需要将日期格式化程序的语言环境设置为英语语言环境。 – rmaddy

+0

@rmaddy你是对的。我已经更新了我的回答 – guidev

+0

酷+1,这是很好的回答:) – Dhiru