Using DateFormatter on a Unix timestamp
You can convert unixTimestamp
to date using Date(timeIntervalSince1970:)
.
let unixTimestamp = 1480134638.0let date = Date(timeIntervalSince1970: unixTimestamp)
If you want to display date in string with specific formate than you can use DateFormatter
like this way.
let date = Date(timeIntervalSince1970: unixtimeInterval)let dateFormatter = DateFormatter()dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you wantdateFormatter.locale = NSLocale.currentdateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you wantlet strDate = dateFormatter.string(from: date)
The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!
.
Simply use TimeZone
instead of NSTimeZone
likedateFormatter.timeZone = TimeZone.current
and your code will work.
You might also remove your / 1000
because 1480134638.0
looks more like seconds than milliseconds (since 1970).
Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.
func getDateFromTimeStamp(timeStamp : Double) -> String { let date = NSDate(timeIntervalSince1970: timeStamp / 1000) let dayTimePeriodFormatter = DateFormatter() dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a" // UnComment below to get only time // dayTimePeriodFormatter.dateFormat = "hh:mm a" let dateString = dayTimePeriodFormatter.string(from: date as Date) return dateString }