Convert Int To Date Formatter value

127 Views Asked by At

Below code I used to convert Int to Time.

//MARK: - Convert Date To String
func dateToString(date: Date, dateFormat: String) -> String {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = dateFormat
    let dateStr = dateFormater.string(from: date)
    return dateStr
}

if let updatedOn = self.dict?["updated_on"]?.intValue{
    var updatedValue = updatedOn/1000
    let timeInterval = TimeInterval(updatedValue)
    let dateValue = Date(timeIntervalSince1970: timeInterval)
    let stringDate =  dateToString(date: dateValue, dateFormat: "MM/dd/yyyy HH:mm:ss a zzz")
    print("stringDate \(stringDate)") // StringDate 11/14/2022 19:05:49 PM GMT+5:30
}

Which print time value. In UI need to shown in this formate "11/14/2022 01:35:49 PM GMT", After converting I am getting "11/14/2022 19:05:49 PM GMT+5:30".

How to convert the resultant stringDate to "11/14/2022 01:35:49 PM GMT" ?

Second Question

Which is standard process to show date Value with timezone as per guidelines?

1

There are 1 best solutions below

0
HangarRash On

If you want the output in GMT (UTC) then set the formatter's timezone to GMT. Apparently you are using your current time zone which happens to be GMT+5:30.

func dateToString(date: Date, dateFormat: String) -> String {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = dateFormat
    dateFormater.timeZone = TimeZone(secondsFromGMT: 0)
    let dateStr = dateFormater.string(from: date)
    return dateStr
}

You should avoid using a hardcoded date format when showing a date to a user. MM/dd/yyyy will confuse most of the world that normally see dd/MM/yyyy. If anything, use a template such as ddMMyyyyHHmmsszzz and let DateFormatter generate the proper locale-specific dateFormat from the template.

I would also suggest not using a with HH. a should only be used with hh.

func dateToString(date: Date, dateFormat: String) -> String {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = DateFormatter.dateFormat(fromTemplate: dateFormat, options: 0, locale: Locale.current)
    dateFormater.timeZone = TimeZone(secondsFromGMT: 0)
    let dateStr = dateFormater.string(from: date)
    return dateStr
}

if let updatedOn = self.dict?["updated_on"]?.intValue{
    var updatedValue = updatedOn/1000
    let timeInterval = TimeInterval(updatedValue)
    let dateValue = Date(timeIntervalSince1970: timeInterval)
    let stringDate =  dateToString(date: dateValue, dateFormat: "MMddyyyyHHmmsszzz")
    print("stringDate \(stringDate)")
}