Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating epoch time in swift

Tags:

ios

swift

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

like image 941
Sam Avatar asked Sep 18 '14 09:09

Sam


People also ask

How do I work with dates and times in Swift 5?

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.

How do I get the epoch date from the timezone offset?

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.

What is epoch time in JavaScript?

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.

What is the use of date struct in Swift?

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.


2 Answers

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.

like image 103
aksh1t Avatar answered Oct 07 '22 02:10

aksh1t


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.

like image 23
Martin R Avatar answered Oct 07 '22 00:10

Martin R