JavaScript date in yyyy-MM-dd format


In order to display date in JavaScript in yyyy-MM-dd format you need to make use of the Date object. You cannot get the date in desired string format in JavaScript as you can in Java, so you have to write few lines of code in order to get the desired date pattern.

Example: JavaScript Date format in yyyy-MM-dd format

<div id="display-date"></div>

<script>
  
  function getDateyyyyMMdd() {
    
   //Step 1: Create a Date object and store it as a constant
    const today = new Date();

   //Step 2: Now from the today, fetch the current day 
   // will return int value that ranges from  1-31
    var day = today.getDate();

   //Step 3: Now from the today, fetch the current month 
   // will return int value that ranges from  0-11
  // 0 implies January, 11 implies December so add add 1
    var month = (today.getMonth() + 1);
    

   //Step 4: If day or month value is less than 9 prefix with zero
    if(day <=9) 
    	day = "0"+day;
    
    if(month <=9) 
      month = "0"+month;
    
         //Step 5: Concatenate the result with the desired hyphen
	 return today.getFullYear() + '-' + month + '-' + day;
  }
  
 document.getElementById("display-date").innerHTML = getDateyyyyMMdd();
</script>
Output:
JavaScript Date format as yyyy-MM-dd
JavaScript Date format as yyyy-MM-dd