Home  >  Article  >  Web Front-end  >  How to Calculate the First and Last Days of the Current Week in JavaScript?

How to Calculate the First and Last Days of the Current Week in JavaScript?

DDD
DDDOriginal
2024-10-19 08:58:30622browse

How to Calculate the First and Last Days of the Current Week in JavaScript?

Getting First and Last Days of the Current Week in JavaScript

When working with dates, it often becomes necessary to determine the first and last days of the current week. JavaScript provides convenient ways to achieve this, as demonstrated below:

Calculating the First and Last Day with Sunday as the Start:

To find the first and last days of the current week starting from Sunday, use the following code:

<code class="js">var curr = new Date();
var first = curr.getDate() - curr.getDay();
var last = first + 6;

var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();</code>

This will calculate the first day as Sunday and the last day as Saturday of the current week.

Adapting for Monday as the Start:

To adjust the calculations for a Monday start, modify the following line:

<code class="js">var first = curr.getDate() - curr.getDay() + 1;</code>

This adds 1 to the calculated first day, ensuring it starts from Monday.

Handling Month Transitions:

As mentioned in the provided answer, handling cases where the first or last day of the week falls in a different month is an exercise left for the user. Here's a hint:

  • Check if the calculated first or last day results in a month different from the current month.
  • Adjust the date accordingly to ensure it stays within the desired month range.

By following these steps, you can easily determine the first and last days of the current week, whether starting on Sunday or Monday.

The above is the detailed content of How to Calculate the First and Last Days of the Current Week in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn