I have the following date variable, which outputs like this:
2021-09-06T00:00:00.000Z
I am trying to check if this date is a monday, if it is, then get the friday date (of that week). if it isn't then get the following weeks monday and friday dates. This is the code i have so far:
startDate = new Date(startDate);
let dayNumber = startDate.getDay();
//if start date is a monday
if (dayNumber == 1) {
//set the end date as the friday
endDate = startDate.setDate(startDate.getDate() 5);
}
//if the start date isn't a monday
else {
let daysTilMonday = 7 - dayNumber;
//find the next monday
startDate = startDate.setDate(startDate.getDate() daysTilMonday);
//set the end date as the friday
endDate = startDate.setDate(startDate.getDate() 5);
}
However i'm getting this error:
TypeError: startDate.getDate is not a function
CodePudding user response:
Date#setDate
set date for itself and return long value of that date
startDate = startDate.setDate(startDate.getDate() daysTilMonday);
//set the end date as the friday
endDate = startDate.setDate(startDate.getDate() 5);
Just don't assign your startDate
and endDate
:
startDate = '2021-09-06T00:00:00.000Z'
startDate = new Date(startDate);
let dayNumber = startDate.getDay();
let endDate;
//if start date is a monday
if (dayNumber == 1) {
//create and set the end date as the friday
endDate = new Date(startDate);
endDate.setDate(endDate.getDate() 5);
}
//if the start date isn't a monday
else {
let daysTilMonday = 7 - dayNumber;
//find the next monday
startDate.setDate(startDate.getDate() daysTilMonday);
//create and set the end date as the friday
endDate = new Date(startDate);
endDate.setDate(endDate.getDate() 5);
}
console.log(startDate);
console.log(endDate);