简体   繁体   中英

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

I need to create few records on Mondays using an api.

And the rule to get the Monday is that it should be either first Monday of a given month or last Monday of the given month.

For example:

If the input date range is 1 Sep 2020 - 30 Sep 2020, I need to pull 28 Sep 2020.

If the input date range is 1 Oct 2020 - 31 Oct 2020, I need to pull 26 Oct 2020.

If the input date range is 1 Nov 2020 - 30 Nov 2020, I need to pull 30 Nov 2020.

If the input date range is 1 Nov 2020 - 31 Dec 2020, I need to pull 28 Dec 2020.

What I did so far is I pulled all the Mondays of given month and stored them in an array. I tried pulling 1st or last Monday of the month, but this works for few months and not for few others.

Hence, I was thinking if I get to know the week of a given day(Monday), which overlaps 2 months, then I can pull that Monday.

So my question is how to get Monday of the week which overlaps 2 months? I am using moment js.

Maybe too late, but it could be helpful for future viewers.

The function takes start and end , but we only use end , so you can get rid of start as all the operations will be on end date in order to get the last monday. To achieve our goal we need to do two simple steps:

  1. Get the end of the month with the end date.
  2. Get the monday of the previous "calculated" date.

For the first step, we use End of Time in order to get the end of the month (the last day).

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

Then we can get the Monday of the week the date is, and we can use Date of Week with the date of previous step.

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.

And taking your examples, we can test our function:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM