To convert a Date
object to a Unix timestamp in Swift, you can use the timeIntervalSince1970
method of the Date
class. Here's an example:
main.swift137 chars4 lines
In the code above, we first create a Date
object representing the current date and time using the Date
constructor with no arguments. Then we call the timeIntervalSince1970
method on the Date
object, which returns the number of seconds since January 1, 1970 (known as the Unix epoch). We then convert the result to an Int
to get a whole number of seconds, and store it in the unixTimestamp
constant. Finally, we print the Unix timestamp to the console for verification.
Note that the Unix timestamp is usually stored as an unsigned 32-bit integer, which can represent dates up to the year 2106. If you need to work with dates beyond that range, you may need to use a different timestamp format.
gistlibby LogSnag