How to convert JavaScript date to string?

Sometimes, we want to convert JavaScript date to string.

In this article, we’ll look at how to convert JavaScript date to string.

How to convert JavaScript date to string?

To convert JavaScript date to string, we use some date methods.

For instance, we write

const temp = new Date();
const dateStr =
  temp.getFullYear().toString().padStart(2, "0") +
  (1 + temp.getMonth()).toString().padStart(2, "0") +
  temp.getDate().toString().padStart(2, "0") +
  temp.getHours().toString().padStart(2, "0") +
  temp.getMinutes().toString().padStart(2, "0") +
  temp.getSeconds().toString().padStart(2, "0");

to get the 4 digit year with getFullYear.

We get the month with 0 for January to 11 for December with getMonth.

We get the date with getDate.

We get the hours with getHours.

We get the minutes with getMinutes.

And we get the seconds with getSeconds.

We convert each number to a string with toString.

Then we call padStart to prepend '0' to each string until it has length 2.

And then we concatenate them all together.

Conclusion

To convert JavaScript date to string, we use some date methods.