. Advertisement .
. Advertisement .
- Use the
Date()constructor by creating a Date object
- Divide the result in seconds by 1000 to get UNIX timestamp
Using Date Constructor with getTime() Method
With the use of the Date constructor to create the date Object, we can convert the date into the UNIX timestamp. The getTime() method is also used, which works just as its name suggests. Take a look at the example to understand it in a simpler way
const dateString1 = '2022-08-22'; const date1 = new Date(dateString1); console.log(date1); // Mon Aug 22 2022 const timestampInMs = date1.getTime(); const unixTimestamp = Math.floor(date1.getTime() / 1000); console.log(unixTimestamp);
In this code, we also applied the formula for dividing milliseconds to convert it into seconds, and then to UNIX timestamp.
In case we have a date string, we can just pass it to the date constructor to get the date object. The string should be formatted correctly to avoid getting an invalid date at the time of creating the date object before passing it to the date constructor.
Math.floor function makes the number round down if it has a decimal or else it returns the number as it is.
console.log(Math.floor(8.99)); // 8 console.log(Math.floor(5.01)); // 5 console.log(Math.floor(5)); // 5
it makes sure, you don’t get a decimal when converting to seconds.
Using MM/DD/YYYY hh:mm:ss Format
When you have a month, day, year, hour, minute, and second, and you want to get the UNIX timestamp, you can use this format. With this, you can get each value to pass as a parameter to the Date constructor. Have a look at the example
const dateString2 = '03/08/2022 14:45:05'; const [dateValues, timeValues] = dateString2.split(' '); console.log(dateValues); // "03/28/2022" console.log(timeValues); // "14:45:05" const [month, day, year] = dateValues.split('/'); const [hours, minutes, seconds] = timeValues.split(':'); const date2 = new Date(+year, month - 1, +day, +hours, +minutes, +seconds); console.log(date2); // Tue Mar 08 2022 14:45:05 const timestampInMs = date2.getTime(); const timestampInSeconds = Math.floor(date2.getTime() / 1000);
Here, we split the time and date string to get the time and date components as a separate string.