0

I'm trying to init a var in JS with date from another JS object but whatever i am trying getting reference to the old object (pointer) and I need it not to change.

var lastActionDate = new Date(mainLastActionDate);
var nowDate = new Date();
var tmpLastActionDate = lastActionDate;

if ((tmpLastActionDate.setDate(tmpLastActionDate.getDate() + 7)) > nowDate)

The last line is the problematic line. I thought that lastActionDate should not be changed and i need it to stay with the old date, but it changes with tmpLastActionDate and i am guessing because it is a pointer.

How can one set a date object by value instead of reference?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Erez
  • 1,933
  • 5
  • 29
  • 56

2 Answers2

2

Try this :

d=new Date()
e=new Date(d.valueOf())
mpm
  • 20,148
  • 7
  • 50
  • 55
  • So simple, thank you, in 5 minutes i will mark your answer as the correct one....so simple, valueOf, stupid me :-) – Erez Apr 10 '12 at 08:28
  • @camus—you can just do `e - new Date(d);`, no need for `valueOf` or `getTime`. – RobG Apr 10 '12 at 09:11
  • I Think I've tried that and didn't work, don't know why....but this one works, 10x – Erez Apr 10 '12 at 10:42
1

You have to clone your original Date object. You can use this method :

var date = new Date();
var copiedDate = new Date(date.getTime());

Reference: How to clone a Date object in JavaScript

Community
  • 1
  • 1
nicopico
  • 3,606
  • 1
  • 28
  • 30