I am trying to get a Saturday to Sunday date range using moment.js. It works up to last line and after that both start and end dates equal to end date.
Using today's date (Nov. 1, 2024), I can see startDate changes to 10/26 (last Saturday) and startDate.add(7, 'd') evaluates to 11/02 but right after both become 11/02.
I think startDate.add(7, 'd') changes startDate first and then assigns it to endDate (I cold be wrong):
var today = moment(new Date());
var startDate;
var endDate;
var weekStart = today.subtract(7, 'd'); // 7 days ago
if (weekStart.day() === 6 ){ // Saturday
startDate = weekStart;
}
else{
startDate = weekStart.day(6);
}
endDate = startDate.add(7, 'd');
The issue you are probably seeing is due to not cloning startDate
and endDate
. You need to clone these because they are referencing the same moment object. When you call startDate.add(7, 'd')
, it modifies startDate
in place, which also affects endDate
since they are pointing to the same object.
To fix this, you could do something like:
var moment = require('moment'); // Import/Require moment
var today = moment(new Date());
var startDate;
var endDate;
var weekStart = today.subtract(7, 'd'); // 7 days ago
if (weekStart.day() === 6) { // Saturday
startDate = weekStart;
} else {
startDate = weekStart.day(6);
}
// Clone startDate to create endDate
endDate = startDate.clone().add(7, 'd');
console.log("Start Date:", startDate.format("MM/DD/YYYY")); // Should show last Saturday
console.log("End Date:", endDate.format("MM/DD/YYYY")); // Should show next Sunday
Using startDate.clone()
, you create a new moment object that is independent of startDate
, so that modifying endDate
does not affect startDate
.