Reputation: 83
I'm trying to set a date like if it was 10 days ago and then I want to create a new date that simply adds 4 days to the first date.
var date_1 = new Date();
date_1.setDate(date_1.getDate() - 10);
var date_2 = date_1;
date_2.setDate(date_2.getDate() + 4);
The problem is that when I print the variables' dates, they have same value. It seems that date_2 modifies also the date_1.
The output are both: Date 2018-05-28 and I want
date_1 = Date 2018-05-24
date_2 = Date 2018-05-28
Upvotes: 0
Views: 37
Reputation: 73291
Simply create a new Date object using date_1's time. Otherwise you're creating a reference only, that will mutate the original object too
const date_1 = new Date();
date_1.setDate(date_1.getDate() - 10);
const date_2 = new Date(date_1);
date_2.setDate(date_2.getDate() + 4);
console.log(date_1, date_2)
Upvotes: 2