Reputation: 263
I want to convert epoche time (number) retrieved from database into a Date Object using Swift 3.
I've got following code for the number
// e.g. 1475616846.424875
user.birthday.timeIntervalSince1970
How can I convert this in a Date object?
Upvotes: 1
Views: 1567
Reputation: 7328
SWIFT 3
This code solve the problem for swift 3.
func epochToLocal(epochTime:Double)->String{
let timeResult:Double = epochTime
let date = NSDate(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
let timeZone = TimeZone.autoupdatingCurrent.identifier as String
dateFormatter.timeZone = TimeZone(identifier: timeZone)
let localDate = dateFormatter.string(from: date as Date)
return "\(localDate)"
}
Upvotes: 1
Reputation: 47876
Check the reference of Date
:
init(timeIntervalSince1970: TimeInterval)
Returns a Date initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds.
Simply use the initializer of Date
:
let epochTime: TimeInterval = 1475616846.424875
let date = Date(timeIntervalSince1970: epochTime)
print(date) //->2016-10-04 21:34:06 +0000
Upvotes: 3