swifttimezonensdateformatterdateformatternsformatter

Convert Int to date formatter followed with timezone


Trying to convert Int to formatted string date with supplied timezone value and formatter to expected result "12/01/2022 09:03:41 PM THA".

//Response Data.

{
      "code": "THA",
      "name": "Thailand Standard Time (THA) (UTC+07)",
      "offset": 25200,
      "utc_offset": "UTC+07",
      "region": "Asia/Phnom_Penh"
}

I have picked Timezone from api response code, Here is what I have implemented.

   var timezoneCode = response.timeZone.code ?? ""

    if let updatedOn = self.dict?["updated_on"]?.intValue{ // i.e., 1669903421000
        let dateValue =  Date(milliseconds: Int64(updatedOn))
        stringDate = dateToStringTimeZone(date: dateValue, dateFormat: "MM/dd/yyyy hh:mm:ss a zzz", timeZone: timezoneCode)
    }

// convert Data To String with Timezone / DateFormate

func dateToStringTimeZone(date: Date, dateFormat: String, timeZone: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone.init(abbreviation: timeZone)
    let dateStr = dateFormatter.string(from: date)
    return dateStr
}

// Date Extension

extension Date {
    var millisecondsSince1970: Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }

    init(milliseconds: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}

After Trying it the above code resultant String date

"12/01/2022 07:33:41 PM GMT+5:30"

Can any one guild how to achive the formatted date value as shown below?

"12/01/2022 09:03:41 PM THA"


Solution

  • Replace "zzz" with your wanted timezone code directly in the date format string

    "MM/dd/yyyy hh:mm:ss a '\(timezoneCode)'"
    

    You also need to use another init for TimeZone, using the offset property seems to work

    let offset = response.timeZone.offset
    dateFormatter.timeZone = TimeZone(secondsFromGMT: offset)