Search code examples
iosswiftdateios13

Wrong date in swift 5 after conversion


I am converting current date into GMT/UTC date string. But every time it returns me with wrong date.

My todays date is 07 February 2020, 11:09:20 AM. You can refer below image.

Current Date

Here is my code :

let apiFormatter = DateFormatter()
//apiFormatter.dateStyle = DateFormatter.Style.long
//apiFormatter.timeStyle = DateFormatter.Style.long
//apiFormatter.calendar = Calendar.current
apiFormatter.timeZone = TimeZone.init(identifier: "GMT") //TimeZone(abbreviation: "UTC") //TimeZone.current //
//apiFormatter.locale = Locale.current
//apiFormatter.dateFormat = "yyyy-MM-DD HH:mm:ss"
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//apiFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"
let endDate = apiFormatter.string(from: Date())
print(endDate)

And what I am getting in return is also you can check in image - 2020-02-38T05:33:34.598Z. I have tried with all the format, but no any luck. Can anyone suggest where it is going wrong?


Solution

  • First of all, the format should be:

    apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    

    The Z is not a literal letter, it's the description of the time zone. However, making it a literal won't probably make a problem.

    The 38 for day from your output is obviously caused by the DD format you have commented out.

    Nevertheless, you have to set the locale:

    apiFormatter.locale = Locale(identifier: "en_US_POSIX")
    

    Otherwise you will have problems with 12/24h switching.

    let apiFormatter = DateFormatter()
    apiFormatter.locale = Locale(identifier: "en_US_POSIX")
    // remove this if you want to keep your current timezone (shouldn't really matter, the time is the same)
    apiFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    let endDate = apiFormatter.string(from: Date())
    print(endDate) // 2020-02-07T08:25:23.470+0000
    print(Date())  // 2020-02-07 08:25:23 +0000
    

    Also note that you can use ISO8601DateFormatter instead of DateFormatter.