Borislav Hadzhiev
Sat Jan 22 2022·2 min read
Photo by Julia Caesar
To convert a date to a Unix timestamp:
Date
object using the Date()
constructor.getTime()
method.1000
.const dateStr = '2022-06-22'; const date = new Date(dateStr); console.log(date); // 👉️ Wed Jun 22 2022 const timestampInMs = date.getTime(); const unixTimestamp = Math.floor(date.getTime() / 1000); console.log(unixTimestamp); // 👉️ 1655856000
We used the
Date()
constructor to create a Date
object.
If you have a date string, pass it to the
Date()
constructor to get a Date
object.
Date
object, you need to format the string correctly before passing it to the Date()
constructor (more on that below).The getTime method returns the number of milliseconds since the Unix Epoch (1st of January, 1970 00:00:00).
getTime()
method by 1000
to convert the milliseconds to seconds.The Math.floor function, rounds a number down if the number has a decimal, otherwise it returns the number as is.
console.log(Math.floor(2.99)); // 👉️ 2 console.log(Math.floor(2.01)); // 👉️ 2 console.log(Math.floor(2)); // 👉️ 2
This ensures that we don't get a decimal when converting the milliseconds to seconds.
If you have difficulties creating a valid Date
object, you can pass 2 types
of parameters to the Date()
constructor:
YYYY-MM-DDTHH:mm:ss.sssZ
, or just
YYYY-MM-DD
, if you only have a date without time.year
, month
(0 =
January to 11 = December), day of the month
, hours
, minutes
and
seconds
.Here is an example where we have a date and time string that is formatted as
MM/DD/YYYY hh:mm:ss
(could be any other format) and pass each individual value
to the Date()
constructor to create a valid Date
and get its Unix timestamp.
// 👇️ Formatted as MM/DD/YYYY hh:mm:ss const dateStr = '09/24/2022 09:25:32'; const [dateComponents, timeComponents] = dateStr.split(' '); console.log(dateComponents); // 👉️ "09/24/2022" console.log(timeComponents); // 👉️ "09:25:32" const [month, day, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, month - 1, +day, +hours, +minutes, +seconds); console.log(date); // 👉️ Sat Sep 24 2022 09:25:32 // ✅ Get Unix timestamp const unixTimestamp = Math.floor(date.getTime() / 1000); console.log(unixTimestamp); // 👉️ 1664000732
The first thing we did was split the date and time string on the space, so we can get the date and time components as separate strings.
We also split the time string on each colon and assigned the hours, minutes and seconds to variables.
Notice that we subtracted 1
from the month when passing it to the Date()
constructor.
Date
constructor expects a zero-based value, where January = 0, February = 1, March = 2, etc.We passed all of the parameters to the Date()
constructor to create a Date
object and got the Unix timestamp by calling the getTime()
method and dividing
the result by 1000
.