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.
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.
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).
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With