JavaScript date in yyyy-MM-dd format

In order to display the date in JavaScript in yyyy-MM-dd (ISO-8601) format you need to make use of the Date object. You cannot get the date in the 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,

Steps to display date in yyyy-MM-dd format JavaScript:

  • 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.
  • 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
  • Step 4: If day or month value is less than 9 prefix with zero
  • Step 5: Concatenate the result with the desired hyphen

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

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

  function getDateyyyyMMdd() {
    const today = new Date();
    var day = today.getDate();
    var month = (today.getMonth() + 1);
    if(day <=9) 
    	day = "0"+day;
    if(month <=9) 
      month = "0"+month;
	 return today.getFullYear() + '-' + month + '-' + day;
 document.getElementById("display-date").innerHTML = getDateyyyyMMdd();
JavaScript Date format as yyyy-MM-dd

Topics Coverage:

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.

Follow Us: GitHub | Facebook | Twitter | Instagram