w3resource

JavaScript: Get the month end date

JavaScript Datetime: Exercise-53 with Solution

Month End Date

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.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that calculates the last day of the month for a given Date object using the Date constructor with day 0 of the next month.
  • Write a JavaScript function that returns the month end date formatted as "MM/DD/YYYY", handling leap years correctly.
  • Write a JavaScript function that validates the month and year inputs before computing the end date.
  • Write a JavaScript function that compares the computed month end date with expected values for verification.

Go to:


PREV : Month Start Date.
NEXT : Check Date in Range.

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.