Search code examples
iosswiftdateformatter

DateFormatter return different time in iOS 14.2 and iOS 16.4


I tried to get the date and time from Timestamp. when I see it in iOS 16+ simulator it shows 04.46 PM whereas in iOS 14.2 it shows 16.47. Is there anything im doing wrong here?

Timestamp value: 1700661033
Date format: "dd-MMM-yyyy HH:mm:ss"
Code Used:

        let timeinterval: TimeInterval = (timeStamp as NSString).doubleValue
        let dateFromServer = NSDate(timeIntervalSince1970: timeinterval)
        let dateFormater = DateFormatter()
        dateFormater.dateFormat = "dd-MMM-yyyy HH:mm:ss"
        return dateFormater.string(from: dateFromServer as Date)

Solution

  • First of all please stop using NS classes if there is a native equivalent.

    To get a reliable result you have to specify a fixed locale either generic en_US_POSIX or your preferred locale.

    let timeinterval = TimeInterval(timeStamp) ?? 0.0
    let dateFromServer = Date(timeIntervalSince1970: timeinterval)
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "dd-MMM-yyyy HH:mm:ss"
    return dateFormatter.string(from: dateFromServer)
    

    And the output depends also on the time zone of the device.