convert a date to a unix timestamp in typescript

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.ts
const date = new Date(); // replace with your own date object
const unixTimeStamp = Math.floor(date.getTime() / 1000);
console.log(unixTimeStamp);
147 chars
4 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