Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js - Get all mondays between a date range

I have a date range that looks like this

let start = moment(this.absence.FromDate);
let end = moment(this.absence.ToDate);

The user can decide to deactivate specific week days during that date range, so I have booleans

monday = true;
tuesday = false;
...

I want to create a function that allows me to put all mondays during my date range in an array.

I've looked around on stack but I can only find help for people who need all the monday from a month for example.

like image 476
Nicolas Avatar asked Jul 04 '17 15:07

Nicolas


People also ask

How do you enumerate dates between two dates in a moment?

To enumerate dates between two dates in Moment and JavaScript, we use a while loop. const enumerateDaysBetweenDates = (startDate, endDate) => { const now = startDate. clone(); const dates = []; while (now. isSameOrBefore(endDate)) { dates.

How do you find the moment of a date range?

js isBetween() Function. It is used to check whether a date is between a range in Moment. js using the isBetween() function that checks if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc).

How do you get the all days in a week in js?

Javascript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

What is MomentJS?

Moment. js is a stand-alone open-source JavaScript framework wrapper for date objects that eliminates native JavaScript date objects, which are cumbersome to use. Moment. js makes dates and time easy to display, format, parse, validate, and manipulate using a clean and concise API.


1 Answers

You can get next Monday using .day(1) and then loop until your date isBefore your end date adding 7 days for each iteration using add

Here a live sample:

//let start = moment(this.absence.FromDate);
//let end = moment(this.absence.ToDate);

// Test values
let start = moment();
let end = moment().add(45 , 'd');

var arr = [];
// Get "next" monday
let tmp = start.clone().day(1);
if( tmp.isAfter(start, 'd') ){
  arr.push(tmp.format('YYYY-MM-DD'));
}
while( tmp.isBefore(end) ){
  tmp.add(7, 'days');
  arr.push(tmp.format('YYYY-MM-DD'));
}
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
like image 124
VincenzoC Avatar answered Nov 15 '22 14:11

VincenzoC