JavaScript(JS) JS format the date

w‮.ww‬theitroad.com

In JavaScript, you can use the Date object along with its built-in methods to format the date in different ways.

Here are some examples of how to format the date:

  1. Formatting the date as "YYYY-MM-DD":
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;

console.log(formattedDate); // e.g. "2023-02-24"
  1. Formatting the date as "MM/DD/YYYY":
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${month}/${day}/${year}`;

console.log(formattedDate); // e.g. "02/24/2023"
  1. Formatting the date with the name of the month:
const date = new Date();
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const monthName = monthNames[date.getMonth()];
const year = date.getFullYear();
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${monthName} ${day}, ${year}`;

console.log(formattedDate); // e.g. "February 24, 2023"

These are just a few examples of how to format the date. You can customize the formatting according to your needs by using different combinations of the Date object's built-in methods.