Reputation: 4284
Am an intermediate-level swift ios developer , now am developing an app where i need to use epoch time that is generated from Current Date and Time, For that i have tried the following code
var date = NSDate()
var timestamp = (floor(date.timeIntervalSince1970 * 1000))
and getting a Float value some thing like 1411032097112.0.. But in my case i need only the integer part of this result. Is this the best way for achieving this or is there any other best solution?
Thank you
Upvotes: 5
Views: 10194
Reputation: 5448
How about
var timestamp = UInt64(floor(date.timeIntervalSince1970 * 1000))
As @MartinR points out in his answer, Int64
will be a better choice than Int
due to space constraint in 32 bit devices. UInt64
will be better still, since you are getting a time interval which will always be positive.
Upvotes: 19
Reputation: 539745
You can just convert the floating point value to Int64
:
let date = NSDate()
let timestamp = Int64(date.timeIntervalSince1970 * 1000.0)
println(timestamp)
// 1411034055289
You should use Int64
or UInt64
instead of Int
because the latter is only 32-bit on 32-bit devices, which is not large enough for the time in milliseconds.
Upvotes: 9