5

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

2 Answers 2

19

How about

var timestamp = UInt64(floor(date.timeIntervalSince1970 * 1000))


Edit :

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.

1
  • 2
    In this case, time interval will always be positive. In general time interval may be negative. Sep 18, 2014 at 15:36
9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.