I needed to convert a Unix Timestamp, which for some inexplicit reason was being returned as a String by an API I was using and this is the super foolish function I ended up with. I am not going to shame the API Provider for returning a timestamp as a String 😉
func createDateTime(timestamp: String) -> String {
var strDate = "undefined"
if let unixTime = Double(timestamp) {
let date = Date(timeIntervalSince1970: unixTime)
let dateFormatter = DateFormatter()
let timezone = TimeZone.current.abbreviation() ?? "CET" // get current TimeZone abbreviation or set to CET
dateFormatter.timeZone = TimeZone(abbreviation: timezone) //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm" //Specify your format that you want
strDate = dateFormatter.string(from: date)
}
return strDate
}
Swift 4: Convert Unix Timestamp to a nicely formatted Date & Time