w3resource

JavaScript: Get the week end date

JavaScript Datetime: Exercise-51 with Solution

Week End Date

Write a JavaScript function to get the week end date.

Sample Solution:

JavaScript Code:

// Define a function called endOfWeek which calculates the ending date of the week for a given input date.
function endOfWeek(date)
  {
    // Calculate the date of the last day of the week by adding the difference between the day of the month and the day of the week, then adding 6.
    var lastday = date.getDate() - (date.getDay() - 1) + 6;
    // Set the date to the calculated last day of the week.
    return new Date(date.setDate(lastday));
  }

// Create a new Date object representing the current date and time.
dt = new Date(); 
// Output the end of the week for the current date and time using the endOfWeek function, converted to a string.
console.log(endOfWeek(dt).toString());

Output:

Sun Jun 24 2018 18:32:20 GMT+0530 (India Standard Time)

Explanation:

In the exercise above,

  • function endOfWeek(date): Declares a function named "endOfWeek()" that takes a 'date' parameter representing the input date.
  • var lastday = date.getDate() - (date.getDay() - 1) + 6;: Calculates the date of the last day of the week by taking the day of the month ('date.getDate()'), subtracting the difference between the day of the week ('date.getDay()') and 1, and then adding 6.
  • return new Date(date.setDate(lastday));: Sets the date to the calculated last day of the week ('lastday') using "date.setDate()" and returns a new Date object representing this updated date.
  • dt = new Date();: Creates a new Date object representing the current date and time.
  • console.log(endOfWeek(dt).toString());: Calls the "endOfWeek()" function with the current date ('dt') and logs the end of the week to the console after converting it to a string.

Flowchart:

Flowchart: JavaScript- Get the week end date

Live Demo:

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


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to get the week start date.
Next: Write a JavaScript function to get the month start date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-date-exercise-51.php