使用 JavaScript 获取下周五的日期

使用 JavaScript 获取下周五的日期

Get the Date of the Next Friday using JavaScript

要获取下周五的日期:

  1. 获取下一个星期五所在月份的日期。
  2. 将结果传递给setDate()方法。
  3. setDate方法更改给定日期的月份中的第几天。
索引.js
function getNextFriday(date = new Date()) { const dateCopy = new Date(date.getTime()); const nextFriday = new Date( dateCopy.setDate( dateCopy.getDate() + ((7 - dateCopy.getDay() + 5) % 7 || 7), ), ); return nextFriday; } // 👇️ Get Friday of Next Week console.log(getNextFriday(new Date())); // 👉️ Fri Jan 21 2022 // 👇️ Get Next Friday for specific Date console.log(getNextFriday(new Date('2022-01-25'))); // 👉️ Fri Jan 28 2022

我们创建了一个可重用的函数,它将一个Date对象作为参数并在下周五返回。

如果未提供参数,则该函数返回当前日期的下一个星期五。

setDate
方法允许我们更改特定
Date实例
月份日期。

The method takes an integer that represents the day of the month.

To get the next Friday, we:

  1. Add 5 to the day of the week, e.g. Tuesday = 7 - 2 (Tuesday) + 5 = 10.
    Note that the
    getDay()
    method returns the day of the week where Sunday is 0, Monday is 1, Tuesday is
    2, etc.

  2. Use the modulo operator to get the remainder of dividing 10 % 7 = 3

  3. If the remainder is equal to 0, then the current date is Friday and we have
    to default it to 7 to get the date of the next Friday.

  4. The getDate() method returns the day of the month, e.g. 18 + 3 = 21,
    where 21 is the day of the month for the next Friday.

If the Date object stores a Friday:

  1. Get the day of the month, e.g. 21.
  2. Calculate 7 - day of the week (Friday = 5) + 5 = 7
  3. Get the remainder – 7 % 7 = 0 || 7 = 7.
  4. 获取下周五的日期 – 21 + 7 = 28,其中28是下周五的日期。

我们在dateCopy函数中创建了变量,因为该setDate方法Date就地改变了实例。

如果您Date在代码的其他地方使用相同的对象,这可能会导致令人困惑的错误。