var date1 = new Date();
date1.setFullYear(2011, 6, 1);
// 2011-07-01, ok
console.log(date1);
// set date2 the same date as date1
var date2 = date1;
// ...
// now I'm gonna set a new date for date2
date2.setFullYear(2011, 9, 8);
// 2011-10-08, ok
console.log(date2);
// 2011-10-08, wrong, expecting 2011-07-01
// I didn't assign a new date to date1
// WHY is date1 changed?
console.log(date1);
“declare date variable in javascript” Code Answervar date = new Date(); //Will use computers date by default.
setDate() method is used to set date of a month into a date object which are created using date() constructor. Syntax: dateObj. setDate(date_Value);
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
Date is object , so it is assigned as reference - simple approach is
date2 = new Date( date1 );
JavaScript uses pass by reference for Dates* (as well as all non-primitives -- var o = {}; var j = o; j.foo = 1; console.log(o.foo); //1
. On the other hand, for Numbers, Strings, and Booleans var o = 0; var j = o; j++; console.log(j); // 0
), so that is expected behavior.
If you need to copy a date you can always
var date2 = new Date( date1.getTime() );
* Please see comments to understand why this is not entirely correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With