2015-10-20 77 views
0

我試圖獲取我的URLResponse的最後修改的屬性作爲NSDate。 我跟着從指令:Swift從NSHTTPURLResponse獲取Last-Modified屬性作爲NSDate

How can I convert string date to NSDate?

Convert String to NSDate in Swift

Date string to NSDate swift

From String to NSDate in Swift

但他們沒有工作。我收到正確的日期從URLResponse-一個String 「Mon,2015年10月19日05:57:12 GMT」形式的對象「

我需要把這個字符串轉換的NSDate,以便能夠將其與的NSDate的形式比較LOCALDATE:2015年10月19日5時57分12秒UTC

我也嘗試過不同的DateFormats但沒」沒有任何區別。

我當前的代碼如下:

//The serverDate needs to match the localDate which is a 
//NSDate? with value: 2015-10-19 05:57:12 UTC 

if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse { 
    let date = httpResp.allHeaderFields["Last-Modified"] as! String //EXAMPLE: "Mon, 19 Oct 2015 05:57:12 GMT" 
    let dateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ" 
    dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") 
    let serverDate = dateFormatter.dateFromString(date) as NSDate? 

    //conversion always fails serverDate == nil  
    println("ServerDate: \(serverDate)")  
} 

任何人都可以解釋爲什麼轉換失敗的原因?有沒有其他方法可以嘗試轉換我的日期?

回答

3

我解決它......

這是一個邏輯問題,因爲我想解析字符串的日期,我必須指定輸入的日期格式接收的正確日期回:從

輸入服務器:字符串= 「星期一,2015年10月19日5時57分12秒GMT」

其在格式的日期: 「EEEE,DD LLL YYYY HH:MM:SS ZZZ」(http://userguide.icu-project.org/formatparse/datetime

- - >工作代碼:

if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse { 
    let date = httpResp.allHeaderFields["Last-Modified"] as! String //EXAMPLE: "Mon, 19 Oct 2015 05:57:12 GMT" 
    let dateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "EEEE, dd LLL yyyy hh:mm:ss zzz" 
    serverDate = dateFormatter.dateFromString(date) as NSDate? 

    //serverDate is now: 2015-10-19 05:57:12 UTC 
    println("ServerDate: \(serverDate)") 
} 
+3

您需要使用HH,而不是hh。否則,當時間爲PM(13-23小時)時,您將得到無效日期。 –

+0

@MikeTaverne隨意編輯它。 –