w3resource

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:

Flowchart: JavaScript- Find out the last day of a month

Live Demo:

See the Pen JavaScript - Find out the last day of a month-date-ex- 9 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that returns the last day of a given month by setting the date to 0 of the following month.
  • Write a JavaScript function that handles leap year logic for February and returns the correct last day.
  • Write a JavaScript function that accepts month and year as parameters, validates them, and outputs the final day of that month.
  • Write a JavaScript function that compares computed last days of different months for verification.

Go to:


PREV : Date Difference in Days.
NEXT : Yesterday's Date.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.