How To Format A Date As yyyy-mm-dd in Javascript

There are some ways to format a date as yyyy-mm-dd in javascript. Let’s learn about it with the explanation and examples below.

Format a date as yyyy-mm-dd in javascript

Method 1: Using the toLocaleString() Method

The toLocaleString() method returns a date object like locale settings.


Date.toLocaleString(locales, options) 


  • locales: Optional. What language format to use? Ex: Australian English is en-Au, Canada English is en-CA.
  • options: Optional. You can set some properties in the object.

Return Value: The return value is a String.


// Create a date object from a date string
var d = new Date();
// en-CA is the Legal value of Canada English
var day = d.toLocaleString("en-CA", { day: "2-digit" });
var month = d.toLocaleString("en-CA", { month: "2-digit" });
var year = d.toLocaleString("en-CA", { year: "numeric" });
// expected output is 2022-09-16 (today)
console.log(year + "-" + month + "-" + day);  



Method 2: Using toISOString method 

The toISOString() method returns a date object as a string, using the ISO standard.



Parameters: None

Return Value: The return value is a String, representing the date using the ISO standard format.


const formatDate = (date) => {
    //Return to Legal Value : Canada English
    return new Date(date).toLocaleDateString('en-CA')
  console.log(formatDate('September 16, 2022'));



Method 3: Creating the Function to format the day


//create a function to format day as YYYY-MM-DD
const Format = (today) => {
  let date = new Date(today);

  //use method getDate() , getMonth, getFullYear 
  let dd = date.getDate().toString(); 
  let mm = (date.getMonth() + 1).toString();
  let yyyy= date.getFullYear();
  //we will insert 0 and month if the month is less than 10 (mean length <2)
  if (mm.length < 2) {
    mm = '0' + mm;

  if (dd.length < 2) {
    dd = '0' + dd;

  return [yyyy, mm, dd].join('-');
console.log(Format('September 15, 2022'));
//it will work if you insert the days in the week
console.log(Format('Sun September 11, 2022'));
// or you can define a variable to get the current day
let today = new Date(); // the current day is September 16, 2022




In this tutorial, we have explained how to format a date as yyyy-mm-dd in javascript using the toISOString() method and the toLocaleString() method. We always hope this tutorial is helpful to you. Leave your comment here if you have questions about Javascript dates. Thanks for your reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *