JavaScript date in yyyy-MM-dd format

In order to display the 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.


  • 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
JavaScript Date format as yyyy-MM-dd

Have Questions? Post them here!

Recent Posts:

Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.