I m trying to get the last-modified property of my URLResponse as NSDate. I followed the instructions from:
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
but none of them worked.. I receive the date properly as a String from the URLResponse-Object in the form of "Mon, 19 Oct 2015 05:57:12 GMT"
I need to convert this String to NSDate to be able to compare it with a localDate in the form of NSDate: 2015-10-19 05:57:12 UTC
I have also tried different dateFormats but it didn't make any difference.
my current code is as follows:
//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)")
}
Can anyone explain why the conversion is failing? Is there any other approach I could try to convert my Date?
Swift 4, XCode 9:
let date = httpResponse.allHeaderFields["Date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, dd LLL yyyy HH:mm:ss zzz"
let serverDate = dateFormatter.date(from: date)
The change to 'HH' suggested by @MikeTaverne is indeed required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With