Hi Friends đź‘‹,

Welcome to Infinitbility ❤️!

Today, we are going to learn How to convert a date to the timestamp in typescript?, here we will use the date built-in method Date.parse() method to convert the date to timestamp format.

So, let’s see what is Date.parse() method is?

The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

Here, there is an easier way of getting the timestamp by using the parse() function. This function returns the timestamp in milliseconds, so we need to divide it by 1000 in order to get the timestamp.

let’s dive into code…

const toTimestamp = (strDate: string) => {
 var datum: number = Date.parse(strDate);
 return datum / 1000;
}

toTimestamp('06/14/2022 11:28:10')

Well, when you run the above code, you can able to see the date convert in timestamp format. For now, let’s check the output.

Output

TypeScript, convert date to timestamp example
TypeScript, convert date to timestamp example

All the best đź‘Ť.