4

Okay consider this bit of code:

var d1 = new Date();
var d2 = d1;

d2.setDate(d2.getDate()+1);
alert(d1 + "\n" + d2);

Even though I call setDate() on d2, d1 is also being incremented. I understand this to be because d1 is assigned to d2 by reference. My question is...how do I NOT do this, so that .setDate() only gets applied to d2?

david
  • 2,529
  • 1
  • 34
  • 50
slinkhi
  • 947
  • 4
  • 16
  • 32

3 Answers3

10

In JavaScript, all objects are assigned to variables 'by reference'. You need to create a copy of the object; Date makes it easy:

var d2 = new Date(d1);

This will create a new date object copying d1's value.

Community
  • 1
  • 1
josh3736
  • 139,160
  • 33
  • 216
  • 263
1

You need

var d2 = new Date(d1.getTime());

See How to clone a Date object in JavaScript for more details.

Community
  • 1
  • 1
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
0

Think this should work:

var d1 = new Date();
var d2 = new Date();
d2.setDate(d1.getDate());

d2.setDate(d2.getDate()+1);
alert(d1 + "\n" + d2);
Andrew Clear
  • 7,910
  • 5
  • 27
  • 35