How to get formatted date time in YYYY-MM-DD HH:mm:ss format using JavaScript?

To get formatted date time in YYYY-MM-DD HH:mm:ss format using JavaScript, we can use some date methods.

For instance, we write

const getFormattedDate = () => {
  const date = new Date();
  const str =
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1) +
    "-" +
    date.getDate() +
    " " +
    date.getHours() +
    ":" +
    date.getMinutes() +
    ":" +
    date.getSeconds();
  return str;
};

to call getFullYear to get the 4 digit year.

We call getMonth to get the month and add 1 to get the human readable month.

We call getDate to get the date.

We call getHours to get the hours.

We call getMinutes to get the minutes.

And we call getSeconds to get the seconds.

Then we concatenate the values together to return the formatted date.