In JavaScript, we can get the last day of the month with the help of the new Date() constructor and come JavaScript code.
var currDate = new Date();
var currMonth = currDate.getMonth();
var currYear = currDate.getFullYear();
var newDate = new Date(currYear, currMonth + 1, 0);
var lastDayOfMonth = newDate.toString();
We first will get the current date using the new Date() object. This will give us the current day, month, and year. We then can use the getMonth() method to get the current month that it is.
We will also get the current year using the getFullYear() method and use this in the next part.
We then use the Date object again but this time to construct a new Date. We want the new date to be the last day of the month. To do this, we will enter the current year as the first parameter, followed by the current month. Since we want to get the last day of the month, what we will have to do is put in the next month, and then for the parameter for the day, we will enter in 0 for that value and it will give us the last day of the previous month.
So as you can see in the code above, we have entered the year, followed by the next month, followed by 0, which will return the last day of the previous month.
//var newDate = new Date(Year,Month,Day);
var newDate = new Date(currYear, currMonth + 1, 0);
We finally use the toString() method so that the date displays in a much friendlier format.
Using JavaScript to Get and Display the Last Day of the Month
Below we will provide code to get the last day of the month in JavaScript, and let the user see it in a friendly format when they click a button.
Here is our HTML set up:
Get Last Day
The last day of the month 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 will then follow the code example at the top of this page to finish getting the day and display it in a friendly format.
Finally, we will show the day to the user by using the textContent property.
function genLastDay(){
var currDate = new Date();
var currMonth = currDate.getMonth();
var currYear = currDate.getFullYear();
var newDate = new Date(currYear, currMonth + 1, 0);
var lastDayOfMonth = newDate.toString();
document.getElementById("theDate").textContent = lastDayOfMonth;
}
The final code and output for this example is below:
Code Output:
The last day of the month is:
Full Code:
Get Last Day
The last day of the month is:
Hopefully this article has been useful in helping you understand how to use JavaScript to get the last day of the month.