The getDate JavaScript method will get the current day of the month from a date object using the getDate() method. It will return a number from 1 to 31.
var currDate = new Date();
var currDay = currDate.getDate();
The value of currDay in the code above would return whatever the day of the month it currently is. The date this post was written was January 16th, so 16 would be the value of currDay.
Getting and Displaying the Current Day, Month, and Year with the Help of the getDate method in JavaScript
Below we will provide code to get the current date in JavaScript, and let the user see it in a friendly format when they click a button.
Today’s Date is:
We will first get the current date using new Date(). Once we have the date object, we can then get the day using the getDate() method, the year using the getFullYear() method, and the month using the getMonth() method.
We can make the date look even better by converting the month number into the month as a String. We just need to make an array with all the months to make this happen, which we will do below.
function genNewDate(){
var currDate = new Date();
var currDay = currDate.getDate();
var currMonth = currDate.getMonth();
var currYear = currDate.getFullYear();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthName = months[currMonth];
document.getElementById("theDate").innerHTML = monthName + ' ' + currDay + ', ' + currYear;
}
The final code and output for this example is below:
Code Output:
Today’s Date is:
Full Code:
Today’s Date is:
<script>
function genNewDate(){
var currDate = new Date();
var currDay = currDate.getDate();
var currMonth = currDate.getMonth();
var currYear = currDate.getFullYear();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthName = months[currMonth];
document.getElementById("theDate").innerHTML = monthName + ' ' + currDay + ', ' + currYear;
}
</script>
Hopefully this article has been useful in helping you understand the getDate Javascript method.