0

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');
asked Nov 1, 2024 at 4:49

1 Answer 1

0

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.

answered Nov 1, 2024 at 5:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.