Search code examples
iosswiftdateswift5ios15

How to convert date from server in Swift?


I have a struct that should give me the correct date from the server but it is nil or time has different with local time like the server return 2021-09-08T20:52:47.001Z but when I want to convert it to swift date it is nil with my code.

import Foundation
struct TimeManager{
    static func editTime(withTime time:String) {
        let serverDateFormatter:DateFormatter = {
            let result = DateFormatter()
            result.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSS"
            result.timeZone = .current
            return result
        }()
        let date = "2021-09-08T20:52:47.001Z"
        let dateformat = serverDateFormatter.date(from: date)
        print(dateformat)
    }
}

I have tested all links in StackOverflow. I have tested this link also link


Solution

  • You need to learn a bit more about how to set the dateFormat string. You forgot the Z in the string. Also as a warning. Creating date formatter objects is extremely expensive. Do not create a new one for every date you want to format. Be sure to cache it and reuse it.

    import Foundation
    
    let serverDateFormatter:DateFormatter = {
        let result = DateFormatter()
        result.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ"
        result.locale = Locale(identifier: "en_US_POSIX")
        result.timeZone = TimeZone(secondsFromGMT: 0)
        return result
    }()
    
    let date = "2021-09-08T20:52:47.001Z"
    let dateformat = serverDateFormatter.date(from: date)
    
    print(dateformat as Any)