JavaScript: Find out the last day of a month
JavaScript Datetime: Exercise-9 with Solution
Last Day of Month
Write a JavaScript function to get the last day of a month.
Test Data:
console.log(lastday(2014,0));
console.log(lastday(2014,1));
console.log(lastday(2014,11));
Output :
31
28
31
Sample Solution:
JavaScript Code:
// Define a JavaScript function called lastday with parameters y (year) and m (month)
var lastday = function(y, m){
// Create a new Date object representing the last day of the specified month
// By passing m + 1 as the month parameter and 0 as the day parameter, it represents the last day of the specified month
return new Date(y, m + 1, 0).getDate();
}
// Output the last day of January 2014
console.log(lastday(2014, 0));
// Output the last day of February 2014
console.log(lastday(2014, 1));
// Output the last day of December 2014
console.log(lastday(2014, 11));
Output:
31 28 31
Explanation:
In the exercise above,
- The code defines a JavaScript function named "lastday()" with two parameters: 'y' for the year and 'm' for the month.
- Inside the function:
- It creates a new Date object representing the last day of the specified month and year.
- To find the last day of the month, it sets the month parameter to 'm + 1' (next month) and the day parameter to '0'. JavaScript handles this by rolling back to the last day of the previous month.
- It retrieves the day component of the resulting Date object using the "getDate()" method, which returns the day of the month (1 to 31).
- The function returns the last day of the specified month as an integer.
- The code then demonstrates the "lastday()" function by calling it with three different month and year combinations:
- January 2014
- February 2014
- December 2014
Flowchart:
Live Demo:
See the Pen JavaScript - Find out the last day of a month-date-ex- 9 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get difference between two dates in days.
Next: Write a JavaScript function to calculate 'yesterday day'.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics