ArticleZip > How To Get First And Last Day Of The Current Week In Javascript

How To Get First And Last Day Of The Current Week In Javascript

If you're working on a project that involves dealing with dates in JavaScript, you might find yourself needing to get the first and last day of the current week. This can be useful for tasks like generating weekly reports or navigating through date ranges. In this article, I'll walk you through a simple approach to achieve this using JavaScript.

To get the first day of the current week, we need to find the date of the most recent Sunday. We can do this by subtracting the current day of the week (0 for Sunday, 1 for Monday, and so on) from the current date.

Javascript

function getFirstDayOfWeek() {
  const currentDate = new Date();
  const currentDayOfWeek = currentDate.getDay();
  const firstDay = new Date(currentDate.getTime() - currentDayOfWeek * 86400000); // 86400000 milliseconds in a day
  return firstDay;
}

The `getFirstDayOfWeek` function retrieves the first day of the current week by subtracting the current day of the week multiplied by the number of milliseconds in a day from the current date.

Next, let's find the last day of the week. We can do this by adding the remaining days of the week to the current date.

Javascript

function getLastDayOfWeek() {
  const currentDate = new Date();
  const currentDayOfWeek = currentDate.getDay();
  const lastDay = new Date(currentDate.getTime() + (6 - currentDayOfWeek) * 86400000); // 6 days remaining from the current day
  return lastDay;
}

In the `getLastDayOfWeek` function, we calculate the last day of the current week by adding the remaining days from the current day to complete the week.

You can now use these functions to get the first and last day of the current week in JavaScript. Here's an example of how you can use them:

Javascript

const firstDay = getFirstDayOfWeek();
const lastDay = getLastDayOfWeek();

console.log("First day of the current week: " + firstDay.toDateString());
console.log("Last day of the current week: " + lastDay.toDateString());

By calling `getFirstDayOfWeek` and `getLastDayOfWeek`, you'll have the dates for the first and last day of the current week, respectively. Feel free to format these dates as needed for your specific use case.

Remember, JavaScript's `Date` object operates within the user's local time zone, so these functions will return dates according to the user's device settings.

In conclusion, getting the first and last day of the current week in JavaScript is straightforward with the right approach. With these simple functions, you can efficiently handle date calculations and make your programming tasks more efficient.