views:

26

answers:

1

How to have a date and subtract 1 year and have a second date for use in display and caculations?

I'm a newbe with JS and find myself fighting the date object
I have declared both currentDate and purchaseDate As var new date() in the globals area But now in a function I try to assign the Original date as "currentDate and the purchaseDate" as one year later,, The alert shows that I have changed the vaue of currentDate rather than just the value of purchaseDate as I intended..

Not what I want! So I get pass by reference vs by value but don't know how to get this so that I have two separate values for the currentDate and the purchaseDate (one year earlier)

currentDate = data.getValue(0,2);
purchaseDate = valueOf(data.getValue(0,2));
purchaseDate.setFullYear(purchaseDate.getFullYear()-1);

alert(purchaseDate);

so this code fails also; That is,, purchase date is 1 year back but so is current date

currentDate = data.getValue(0,2);
    purchaseDate = data.getValue(0,2);
            purchaseDate.setFullYear(purchaseDate.getFullYear()-1);
alert(purchaseDate);
+1  A: 

The code which you posted is too ambiguous to reliably point the root cause of your problem (it's unclear what valueOf() is doing), but basically, you indeed need to create a new Date instance based on the time of the other Date. Here's how you could do this, assuming that currentDate is a real Date as well.

var purchaseDate = new Date(currentDate.getTime());

Here's a full kickoff example:

var currentDate = new Date();
var purchaseDate = new Date(currentDate.getTime());
purchaseDate.setFullYear(purchaseDate.getFullYear() - 1);
alert(currentDate); // Today.
alert(purchaseDate); // Today minus one year.
BalusC
The problem with that code is that it assumes that the two dates are independent I need to calculate one date from the other and that is why the reference issue pops up Even if I drop the valueOF, which I was doing to try to force a new instance. So I need to get currentDate From a table As indicated then calculate the purchaseDate as 1 year back from the date I got from the table,, so it is not based on system date...rather one that I'm getting via Ajax query. All attempt so far seem to pass references so both currentDate and purchaseDate get changed
dartdog
So, `var purchaseDate = new Date(currentDate.getTime());` did not work for you? By the way, the full example is just a kickoff example. You just have substitute the example with values of your situation. E.g. `var currentDate = data.getValue(0,2);`. Since I have no idea what the `data.getValue(0,2)` is doing, I didn't include it in the example to avoid red herrings. As long as it returns `Date`, the above should work.
BalusC