Sometimes, we want to convert seconds to a date object with JavaScript.
In this article, we’ll look at how to convert seconds to a date object with JavaScript.
How to convert seconds to a date object with JavaScript?
To convert seconds to a date object with JavaScript, we create a date with timestamp 0 and add the seconds we want to it.
For instance, we write
const toDateTime = (secs) => {
const t = new Date(1970, 0, 1);
t.setSeconds(secs);
return t;
};
to define the toDateTime
function.
In it, we create a date with timestamp 0.
Then we call setSeconds
to add secs` seconds to it.
Finally we return the t
date.
Conclusion
To convert seconds to a date object with JavaScript, we create a date with timestamp 0 and add the seconds we want to it.