Requirement: Given a start and end date, we need to find out which days of the week exist between them i.e. Sun, Mon, Tue, Wed, Thu, Fri, Sat (in numbers: 0, 1, 2, 3, 4, 5, 6). We might also want to count them, or we may only be interested if weekends exist.
This usually is required in forms where we want to create something recurring or in bulk, and we need to know if a particular weekday comes between the user-selected dates.
Below is the code with explanation, using both JavaScript date and moment js.
Get Days of Week Between Two Dates
1. With JavaScript Date
const getDaysOfWeekBetweenDates = (sDate = "2021-07-18", eDate = "2021-07-20") => {
const startDate = new Date(sDate)
const endDate = new Date(eDate);
endDate.setDate(endDate.getDate() + 1);
const daysOfWeek = [];
let i = 0;
while (i < 7 && startDate < endDate) {
daysOfWeek.push(startDate.getDay());
startDate.setDate(startDate.getDate() + 1);
i++;
}
return daysOfWeek;
};
getDaysOfWeekBetweenDates("2021-07-01", "2021-07-04"); // => [ 4, 5, 6, 0 ]
getDaysOfWeekBetweenDates("2021-07-15", "2021-07-29"); // => [ 4, 5, 6, 0, 1, 2, 3 ]
getDaysOfWeekBetweenDates("1999-01-01", "1999-01-06"); // => [ 5, 6, 0, 1, 2, 3 ]
getDaysOfWeekBetweenDates("2011-06-11", "2007-06-18") // => []
2. With Moment JS
const moment = require("moment");
const getDaysOfWeekBetweenDates = (sDate = "2021-07-18", eDate = "2021-07-20") => {
const startDate = moment(sDate)
const endDate = moment(eDate);
endDate.add(1, "day");
const daysOfWeek = [];
let i = 0;
while (i < 7 && startDate < endDate) {
daysOfWeek.push(startDate.day());
startDate.add(1, "day");
i++;
}
return daysOfWeek;
};
getDaysOfWeekBetweenDates("2021-07-02", "2021-07-05"); // => [ 5, 6, 0, 1 ]
getDaysOfWeekBetweenDates("2010-07-20", "2010-07-28"); // => [ 2, 3, 4, 5, 6, 0, 1 ]
getDaysOfWeekBetweenDates("1999-06-12", "1999-06-17"); // => [ 6, 0, 1, 2, 3, 4 ]
getDaysOfWeekBetweenDates("2015-06-11", "2000-06-16") // => []
The Code Explained
In both methods above, the steps remain the same:
- Create a new Date or moment object for start and end dates
- Add 1 day to the end date, because we want to include the end day in our calculation
- initialize empty
daysOfWeek
array andi
counter - add
while
loop that checks the counter is less than 7 (because maximum days of week equal 7), and that startDate is smaller than endDate - Inside the
while
loop we push the day intodaysOfWeek
array, add 1 day to startDate, and increment thei
counter - finally, return
daysOfWeek
array
Return Object Instead of Array
Note that we can also use an object hash to store 0 to 6 and assign them true if the day is found. From the above moment example, we’ll replace the following part:
const daysOfWeek = {};
let i = 0;
while (i < 7 && startDate < endDate) {
daysOfWeek[startDate.day()] = true;
startDate.add(1, "day");
i++;
}
return daysOfWeek;
And the result for the same calls will become:
getDaysOfWeekBetweenDates("2021-07-02", "2021-07-05");
// => { '0': true, '1': true, '5': true, '6': true }
getDaysOfWeekBetweenDates("2010-07-20", "2010-07-28");
/*
=> {
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true
}
*/
getDaysOfWeekBetweenDates("1999-06-12", "1999-06-17")
// => { '0': true, '1': true, '2': true, '3': true, '4': true, '6': true }
getDaysOfWeekBetweenDates("2015-06-11", "2000-06-16") // => {}
Return Day Names Instead of Numbers
For that, modify the above code a little, and use dayNames
array of day names:
const dayNames = [
"sun",
"mon",
"tue",
"wed",
"thu",
"fri",
"sat"
]; // add this at the top
daysOfWeek.push(dayNames[startDate.getDay()]); // modify this inside while loop
// OR in case of returning the hash
daysOfWeek[dayNames[startDate.day()]] = true;
The results will now be something like:
// array
// => [ 'fri', 'sat', 'sun', 'mon', 'tue', 'wed' ]
// hash
// => {
// sat: true,
// sun: true,
// mon: true,
// tue: true,
// wed: true,
// thu: true
// }
What Questions Can Be Answered From This Data?
We can use the returned array or hash to answer questions about days of the week such as:
Does Thursday Exist?
// array
daysOfWeek.includes(4) // => true or false
// hash
daysOfWeek[4] // => true or undefined
Does a Weekend Exist?
// array
daysOfWeek.includes(0) || daysOfWeek.includes(6)
// hash
daysOfWeek[0] || daysOfWeek[6]
Do a Saturday & Sunday Both Exist (Complete Weekend Exist?)
// array
daysOfWeek.includes(0) && daysOfWeek.includes(6)
// hash
daysOfWeek[0] && daysOfWeek[6]
Does No Weekend Exist? (Only Weekdays Exist?)
// array
!daysOfWeek.includes(0) && !daysOfWeek.includes(6)
// hash
!daysOfWeek[0] && !daysOfWeek[6]
Count Days of Week Between Two Dates
With little modification to our original code, we can keep and increment the count of all days of the week between two dates.
1. With JavaScript Date
const countDaysOfWeekBetweenDates = (
sDate = "2021-07-18",
eDate = "2021-07-20"
) => {
const startDate = new Date(sDate)
const endDate = new Date(eDate);
endDate.setDate(endDate.getDate() + 1);
// initialize each day with 0
const daysOfWeekCount = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
};
while (startDate < endDate) {
daysOfWeekCount[startDate.getDay()] = daysOfWeekCount[startDate.getDay()] + 1;
startDate.setDate(startDate.getDate() + 1);
}
return daysOfWeekCount;
};
2. With Moment JS
const countDaysOfWeekBetweenDates = (
sDate = "2021-07-18",
eDate = "2021-07-20"
) => {
const startDate = moment(sDate)
const endDate = moment(eDate);
endDate.add(1, "day");
const daysOfWeekCount = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
};
while (startDate < endDate) {
daysOfWeekCount[startDate.day()] = daysOfWeekCount[startDate.day()] + 1;
startDate.add(1, "day");
}
return daysOfWeekCount;
};
Results
Calling countDaysOfWeekBetweenDates
returns us an object hash with keys from 0 to 6, and the count of each day against them, within the given start and end date.
countDaysOfWeekBetweenDates("2000-01-01", "2021-01-01");
/*
=> {
'0': 1096,
'1': 1096,
'2': 1096,
'3': 1096,
'4': 1096,
'5': 1096,
'6': 1096
}
*/
countDaysOfWeekBetweenDates("1900-01-01", "1999-12-31");
/*
=> {
'0': 5217,
'1': 5218,
'2': 5218,
'3': 5218,
'4': 5218,
'5': 5218,
'6': 5217
}
*/
countDaysOfWeekBetweenDates("2021-01-01", "2021-07-01");
/*
=> {
'0': 26,
'1': 26,
'2': 26,
'3': 26,
'4': 26,
'5': 26,
'6': 26
}
*/
From the result object, we can tell the count of any day of the week, or a combination of them, individually. For example:
Count Sundays Since the Beginning of the Calendar
const weekDaysCount = countDaysOfWeekBetweenDates("0000-01-01", new Date());
weekDaysCount[0]; // => 105480
Count Weekends Between World War 1 & World War 2
const weekDaysCount = countDaysOfWeekBetweenDates("1918-11-11", "1939-10-31");
weekDaysCount[0] + weekDaysCount[6] // => 2188
Although there are other one-liners for finding that, we can also sum all the days of the week and get the total number of days between two dates. For example:
Count Days Between World War 1 & World War 2
const weekDaysCount = countDaysOfWeekBetweenDates("1918-11-11", "1939-10-31");
weekDaysCount[0] +
weekDaysCount[1] +
weekDaysCount[2] +
weekDaysCount[3] +
weekDaysCount[4] +
weekDaysCount[5] +
weekDaysCount[6]
// => 7660
See also
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Date Format Validation With Moment JS
- Yup Number Validation: Allow Empty String
- Exactly Same Query Behaving Differently in Mongo Client and Mongoose
- JavaScript Unit Testing JSON Schema Validation
- Reduce JS Size With Constant Strings
- JavaScript SDK