Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get Last-Modified property from NSHTTPURLResponse as NSDate

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?

like image 306
Jan Raufelder Avatar asked Oct 18 '25 23:10

Jan Raufelder


1 Answers

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.

like image 63
John Difool Avatar answered Oct 20 '25 12:10

John Difool