Current Date in yyyy-mm-dd Format with JavaScript

In this tutorial we will learn how to Get Current Date in yyyy-mm-dd Format with JavaScript. JavaScript new Date() Constructor, getDate() method, getMonth() method and getFullYear() method can be used for this.

JavaScript new Date() Constructor

JavaScript new Date() Constructor creates a date object which represents current date and time.

The new Date() Constructor returns the date object which has current time in milliseconds from 1st January 1970 UTC till current date.

JavaScript getDate() method

JavaScript getDate() method returns the current day of the month from 1 to 31.

JavaScript getMonth() method

JavaScript getMonth() method returns the current month of the year, the values range from 0 to 11, where 0 represents the first month and so on. That is why we add 1 to the value of month to display the accurate month of current date.

JavaScript getFullYear() method

JavaScript getFullYear() method returns the year of the current date in four digit format from 0000 to 9999.

HTML Code

HTML Code is given below, in this code we have a paragraph tag to display the current date in yyyy-mm-dd format while a Button tag is used to execute a JavaScript function.

<p id="output"></p>
<button onclick="getDate()">Get Date</button>    

JavaScript Code

Take a look at the JavaScript code.

<script>
function getDate()
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth()+1; 
var year = date.getFullYear();
if(day<10) 
{
    day='0'+day;
} 
if(month<10) 
{
    month='0'+month;
} 
var currentDate = year + '-' + month + '-' + day;    
document.getElementById('output').innerHTML = currentDate;
}
</script>

Demo

How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript