How to format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js?

Sometimes, we want to format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js.

In this article, we’ll look at how to format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js.

How to format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js?

To format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js, we can use the toISOString method.

For instance, we write

new Date().toISOString()
  .replace(/T/, ' ')
  .replace(/..+/, '')

to call toISOString on a Date instance.

Then we replace the T and the periods with a space and empty string respectively.

Conclusion

To format a UTC date as a ‘YYYY-MM-DD hh:mm:s’ string using Node.js, we can use the toISOString method.