Search code examples
swiftnsdateeventkit

Swift convert Unix timestamp to Date with timezone and save it to EKEvent


I trying to convert my unix timestamp(Int) to the Date type in my app. I found a solution which is

let str = timeValue as? NSNumber
return Date(timeIntervalSince1970: str.doubleValue)

This solution works but how can I set the timezone. I found another solution that used the formatter but the formatter return string.

func convertDateTime(timeValue: Int) -> String {
    let truncatedTime = Int(timeValue)
    let date = Date(timeIntervalSince1970: TimeInterval(truncatedTime))
    let formatter = DateFormatter()
    formatter.timeZone = TimeZone(abbreviation: "GMT+8")
    formatter.dateFormat = "dd/MM/yyyy hh:mm a"

    return formatter.string(from: date)
}

Anyone can answer me how to do so?

Edited: I want to save it as EKEvent.


Solution

  • Dates represent instants/points in time - "x seconds since a reference point". They are not "x seconds since a reference point at a location", so the timezone is not part of them. It makes no sense to "set the timezone of a Date", the same way it makes no sense to "set the number of decimal places of a Double".

    It seems like you actually want to store a EKCalendarEvent. Well, EKCalendarEvents do have a timezone, because they are events that occur at a particular instant/day (occurrenceDate), in some timezone (timeZone). So you just need to set the timeZone property of the EKEvent, rather than the Date.