Categories
JavaScript Answers

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

Spread the love

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.

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 *