How to Get Last Friday’s Date in JavaScript

Finding the last Friday’s date from the current date is a common task in scheduling, reporting, and other time-related applications. JavaScript provides several methods to easily calculate this.

let today = new Date();
let lastFriday = new Date(today.setDate(today.getDate() - (today.getDay() + 2) % 7));
console.log(lastFriday);

To find the last Friday from the current date in JavaScript, you can use this code snippet:

Getting the date for the last Friday can be useful in many scenarios, such as generating weekly reports or scheduling tasks. This guide explains how to calculate the last Friday’s date in JavaScript, ensuring accuracy and reliability.

Understanding the getDay() Method

The getDay() method in JavaScript returns the day of the week for a given date as an integer (0 for Sunday, 1 for Monday, and so on). This method is central to calculating the last Friday’s date.

Calculating Last Friday’s Date

To calculate the last Friday’s date, you can use the getDay() method to determine the current day of the week and then adjust the date accordingly.

Example: Get Last Friday’s Date

Here’s how you can find the last Friday from today’s date:

let today = new Date();
let lastFriday = new Date(today.setDate(today.getDate() - (today.getDay() + 2) % 7));
console.log(lastFriday);

Explanation:

  • new Date(): Creates a new Date object representing the current date.
  • today.getDay(): Retrieves the current day of the week as an integer (0-6).
  • today.setDate(today.getDate() - (today.getDay() + 2) % 7): Calculates the difference between today and the last Friday by subtracting the appropriate number of days.
  • (today.getDay() + 2) % 7: Calculates how many days to subtract to get to the last Friday. The +2 adjusts the calculation since Friday is the 5th day of the week, and we subtract the difference.
  • console.log(lastFriday): Prints the date for last Friday.

Handling Edge Cases

JavaScript handles the date adjustments automatically, including month boundaries and leap years. For example:

Example:

let date = new Date('2024-01-01'); // Monday, January 1st, 2024
let lastFriday = new Date(date.setDate(date.getDate() - (date.getDay() + 2) % 7));
console.log(lastFriday); // Friday, December 29th, 2023

This calculation correctly identifies the last Friday even when crossing month boundaries.

Conclusion

Calculating the last Friday’s date in JavaScript is simple and effective using the getDay() method along with date arithmetic. Whether you’re dealing with reports, schedules, or any other date-related tasks, mastering this technique ensures your code is both accurate and robust. By understanding how to manipulate dates in JavaScript, you can confidently handle a wide range of time-based operations in your projects.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top