Search code examples
iosswiftnsdateformatter

Swift: Date() to UTC global time string


Hi I want to convert Date() into string by following this format exactly 2020-07-29T05:27:04.000Z.

Tried1:

let dateFormatter = DateFormatter()
                  
    dateFormatter.calendar = Calendar(identifier: .iso8601)
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
    let string = dateFormatter.string(from: Date())
    
    print("String: \(string)")

Output 1: 2020-08-06T10:14:25.890Z

Tried2:

let formatter = ISO8601DateFormatter()
    formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    let string =  formatter.string(from: Date())
    
    print("String: \(string)")

Output2: 2020-08-06T10:17:33.508Z

But I want to get string that exactly matches to 2020-07-29T05:27:04.000Z this format. Please help me to find out. Thanks in advance.


Solution

  • Just replace SSS with 000

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000XXXXX"