2016-06-09 40 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