Borislav Hadzhiev
Last updated: Jan 27, 2022
Check out my new book
To get the current date and time in seconds:
Date
object using the Date()
constructor.geTime()
method.1000
.const date = new Date(); const dateTimeInSeconds = Math.floor(date.getTime() / 1000); // 👇️ 164328461 console.log(dateTimeInSeconds);
We used the
Date()
constructor to create a Date
object that represents the current date and time.
The getTime method returns the number of milliseconds since the Unix Epoch (1st of January, 1970 00:00:00).
We can convert the milliseconds to seconds, by dividing the number by 1000
.
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(7.99)); // 👉️ 7 console.log(Math.floor(7.01)); // 👉️ 7 console.log(Math.floor(7)); // 👉️ 7
This ensures that we don't get a decimal when converting the milliseconds to seconds.
Make sure to pass the result from the division to the Math.floor
function,
because the number might have a decimal when converted to seconds.
If you need to create a Date
object from a timestamp in seconds, multiply it
by 1000
and pass it to the Date()
constructor.
const dateTimeInSeconds = 1642923027; const date = new Date(dateTimeInSeconds * 1000); console.log(date); // 👉️ Sun Jan 23 2022 09:30:27
Since the Date()
constructor expects a value in milliseconds, we have to
convert the seconds back to milliseconds when creating a Date
object.
You can use this approach to get the date and time in seconds for any date.
const date = new Date('2022-02-24T09:30:47'); console.log(date); // 👉️ Thu Feb 24 2022 09:30:47 const dateTimeInSeconds = Math.floor(date.getTime() / 1000); // 👇️ 1645687847 console.log(dateTimeInSeconds);
We created a date object for the 24th of February 2022 and got the date and time in seconds using the same approach.
You can also use multiple, comma-separated parameters when creating a Date
.
const date = new Date(2022, 0, 23, 9, 30, 27); console.log(date); // 👉️ Sun Jan 23 2022 09:30:27 const dateTimeInSeconds = Math.floor(date.getTime() / 1000); // 👇️ 1642923027 console.log(dateTimeInSeconds);
We passed the year
, month
(January = 0, February = 1, etc), day
, hour
,
minutes
and seconds
as parameters to the Date()
constructor.
Note that the month is a zero-based value from 0
(January) to 11
(December).