w3resource

JavaScript: Get the month end date

JavaScript Datetime: Exercise-53 with Solution

Write a JavaScript function to get the month end date.

Sample Solution:

JavaScript Code:

// Define a function called endOfMonth that takes a Date object 'date' as input
function endOfMonth(date)
  {
    // Create a new Date object representing the last day of the month of the provided date
  return new Date(date.getFullYear(), date.getMonth() + 1, 0);
 
  }

// Create a new Date object representing the current date and time
dt = new Date(); 

// Output the last day of the month for the provided date
console.log(endOfMonth(dt).toString());

Output:

Sat Jun 30 2018 00:00:00 GMT+0530 (India Standard Time)

Explanation:

In the exercise above,

  • The function "endOfMonth()" takes a 'date' parameter, which is a Date object.
  • Inside the function, it creates a new Date object representing the last day of the month of the provided date.
  • The 'new Date()' constructor is used with three arguments: the year (date.getFullYear()), the next month (date.getMonth() + 1), and day 0 of that month (which represents the last day of the previous month).
  • Finally, the function returns the newly created Date object representing the last day of the month.

Flowchart:

Flowchart: JavaScript- Get the month end date

Live Demo:

See the Pen JavaScript - Get the month end date-date-ex-53 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to get the month start date.
Next: Check if a date is between two other dates.

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.