To convert a Date
object to a Unix timestamp in TypeScript, we need to get the number of milliseconds since January 1, 1970, 00:00:00 UTC (Unix epoch time) using the getTime()
method of the Date
object, and then divide it by 1000 to get the Unix timestamp in seconds. Here's the code:
index.ts147 chars4 lines
In the code above, we first create a new Date
object representing the current date and time, and then use the getTime()
method to get the number of milliseconds elapsed since Unix epoch time. We then divide this number by 1000 and round it down using Math.floor()
to get the Unix timestamp in seconds.
Note that some APIs may require or return Unix timestamps in milliseconds instead of seconds, in which case you don't need to divide by 1000.
gistlibby LogSnag