如何使用 moment js 获取与 2 个月重叠的一周中的星期一?

How to get monday of the week which overlaps 2 months using moment js?

我需要在星期一使用 api 创建一些记录。

获得星期一的规则是它应该是给定月份的第一个星期一或给定月份的最后一个星期一。

例如:

如果输入的日期范围是2020年9月1日-2020年9月30日,我需要拉2020年9月28日。

如果输入的日期范围是2020年10月1日-2020年10月31日,我需要拉2020年10月26日。

如果输入的日期范围是2020年11月1日-2020年11月30日,我需要拉到2020年11月30日。

如果输入的日期范围是2020年11月1日-2020年12月31日,我需要拉2020年12月28日。

到目前为止我所做的是提取给定月份的所有星期一并将它们存储在一个数组中。我尝试拉动每个月的第一个或最后一个星期一,但这几个月有效,而其他少数人则无效。

因此,我在想如果我知道给定一天(星期一)的星期,它重叠 2 个月,那么我可以拉那个星期一。

所以我的问题是如何获得与 2 个月重叠的一周中的星期一?我正在使用 moment js.

也许为时已晚,但它可能对未来的观众有所帮助。

该函数采用startend,但我们只使用end,所以你可以去掉start,因为所有的操作都会在end 日期以获得最后一个星期一。为了实现我们的目标,我们需要做两个简单的步骤:

  1. 获取 end 日期的月末。
  2. 获取上一个“计算”日期的星期一。

第一步,我们使用End of Time来获取月末(最后一天)。

Mutates the original moment by setting it to the end of a unit of time.

然后我们可以得到这个日期是星期几,我们可以用Date of Week和上一步的日期

Gets or sets the day of the week. [...] As of 2.1.0, a day name is also supported. This is parsed in the moment's current locale.

并以您的示例为例,我们可以测试我们的功能:

function lastMonday(start, end) {
  console.log('Start is ', moment(start).format('LL'));
  console.log('End is ', moment(end).format('LL'));
  return moment(end).endOf('month').day('Monday');
}

console.log('Last monday is', lastMonday('2020-09-01', '2020-09-30').format('LL'));
console.log('Last monday is', lastMonday('2020-10-01', '2020-10-31').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-11-30').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-12-31').format('LL'));
<script src="https://momentjs.com/downloads/moment.js"></script>