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
The great thing about working with dates and times in Swift 5 is that the Calendar class is that it does its best to work with the DateComponents that you give it, and DateComponents gives you all sorts of ways to specify a date.
The Epoch calculation approach subtracts the total timezone offset in seconds from the Date () object given by Foundation. This calculation will result in an Epoch date that can be converted to a Date object using the timeIntervalSince1970 API.
epoch time is Unix style in milli seconds since 01/01/1971, that means it returns long number in milli seconds, This is epoch time or unix timestamp Javascript provides Date object provides date and time related things. Note: Javascript runs on client and server side.
The Date struct, which stores date and times in Swift 5. The Calendar struct, which represents one of 16 different calendar systems, and provides a meaningful context for Date s. The DateComponents struct, which a collection of date and time components, such as years, months, days, hours, minutes, and so on.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With