Categories
JavaScript Answers

How to convert seconds to a date object with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *