Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date variable assignment

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);
like image 235
railOne Avatar asked Jul 07 '11 11:07

railOne


People also ask

How do you declare a Date variable in JavaScript?

“declare date variable in javascript” Code Answervar date = new Date(); //Will use computers date by default.

How do you assign a Date to a variable in node JS?

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);

Is there a Date data type in JavaScript?

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.


2 Answers

Date is object , so it is assigned as reference - simple approach is

date2 = new Date( date1 );
like image 91
SergeS Avatar answered Sep 20 '22 04:09

SergeS


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.

like image 27
cwallenpoole Avatar answered Sep 21 '22 04:09

cwallenpoole