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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.