Reputation: 1593
I am using javascript setDate
method to do some date manipulation due to which my value of originalDate
value is lost. Here is what I am trying :
var originalDate = new Date();
var newDate = originalDate;
newDate.setDate(15);
I want that setDate()
should only update newDate
variable, not the originalDate. How can I do that.
Thanks.
Upvotes: 0
Views: 498
Reputation: 23502
Your problem is that you are assigning the reference of originalDate
to newDate
, so they both point at the same Date
object.
Another possibility:
Javascript
function cloneDate(dateObject) {
return new Date(dateObject.valueOf());
}
var originalDate = new Date(),
newDate = cloneDate(originalDate);
newDate.setDate(15);
console.log(originalDate);
console.log(newDate);
Output
Tue Feb 25 2014 07:13:53 GMT+0100 (CET) Sat Feb 15 2014 07:13:53 GMT+0100 (CET)
On jsFiddle
This creates newDate
with same value as originalDate
, but now they are 2 distinct objects
.
Upvotes: 3
Reputation: 9635
try this
var originalDate = new Date();
var newDate = new Date();
newDate.setDate(15);
Upvotes: 0