我試圖獲取我的URLResponse的最後修改的屬性作爲NSDate。 我跟着從指令:Swift從NSHTTPURLResponse獲取Last-Modified屬性作爲NSDate
How can I convert string date to NSDate?
Convert String to NSDate in 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)")
}
任何人都可以解釋爲什麼轉換失敗的原因?有沒有其他方法可以嘗試轉換我的日期?
您需要使用HH,而不是hh。否則,當時間爲PM(13-23小時)時,您將得到無效日期。 –
@MikeTaverne隨意編輯它。 –