0

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

1 Answers1

3

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)
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • there is one other problem the time from the server is not true with the time zone I have. for example, time from the server is 6:00:00 but now is 12:00:00 how fix this problem? – Mohammadhossein Ghadamyari Oct 02 '21 at 06:56
  • It's highly recommended to specify first the locale then the date format. @MohammadhosseinGhadamyari The date format on the server is in UTC (indicated by the `Z`). Use another date formatter to convert the date to your local time zone. – vadian Oct 02 '21 at 07:06
  • What should I do? Do you mean to create another date formatted to fix this problem? – Mohammadhossein Ghadamyari Oct 02 '21 at 07:08
  • Yes, create another `DateFormatter` with the format you want to display (or use the same one just by modifying the date format). The formatter considers the local time zone by default. Setting the time zone to UTC explicitly in the formatter is pointless anyway because the date string has a fixed time zone. – vadian Oct 02 '21 at 07:21
  • [Read these docs](https://developer.apple.com/documentation/foundation/dateformatter). Specifically, the part titled "Working With User-Visible Representations of Dates and Times". – Daniel T. Oct 02 '21 at 11:19