Search code examples
iosswiftnsdateformatter

Swift datefomatter returns wrong time


I am working in iOS app with Dateformatter which is return wrong time. I don't have any idea to fix this. Can anyone please correct me to get correct time?

let dateString = "2020-08-11T05:32:33.000Z"

func approach1(){
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
          
    guard let date = dateFormatter.date(from: dateString) else {fatalError()}
    
    printTime(date: date)
}

func approach2(){
    
    let dateFormatter = ISO8601DateFormatter()
    dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    guard let date = dateFormatter.date(from: dateString) else { fatalError()}
      
    printTime(date: date)
}

func printTime(date: Date){
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.amSymbol = "AM"
    dateFormatter.pmSymbol = "PM"
    let time  = dateFormatter.string(from: date)

    print("date: \(date)")
    print("Time: \(time)") // Here it's always wrong time with those approach.
}

Current Result:

enter image description here


Solution

  • There's nothing wrong. The date formatter returns the correct time

    The date string

    "2020-08-11T05:32:33.000Z"

    represents a date in UTC(+0000).

    Your local time zone is obviously UTC+0530. DateFormatter considers the local time zone by default.

    To format the time also in UTC you have to set the time zone of the date formatter explicitly

    func printTime(date: Date) {
        
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        dateFormatter.dateFormat = "h:mm a"
        dateFormatter.amSymbol = "AM"
        dateFormatter.pmSymbol = "PM"
        let time  = dateFormatter.string(from: date)
    
        print("date: \(date)")
        print("Time: \(time)")
    }