I am just starting with dateJS and it seems like a great lib but I am obviously missing something (probably a stupid mistake) but in my function I need 3 dates: clickedDate, weekStart & weekEnd. But using dateJS I seem to be overwritting each variable. Can someone please point out my mistake?
var clickDate = myDate;
console.log(clickDate);
var weekStart = Date.parse(clickDate).last().monday();
console.log(clickDate);
var weekEnd = Date.parse(clickDate).next().sunday();
console.log(weekEnd);
console.log('break');
console.log(clickDate);
console.log(weekStart);
console.log(weekEnd);
The console shows the following
Date {Wed Nov 30 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Mon Nov 28 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
break
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
This isn't an issue with Datejs, but a feature(?) of JavaScript Date objects. In JavaScript, the Date object is mutable, and setting a Date
object value to a new variable creates a reference to the original, not a new object.
This can be demonstrated using plain old JavaScript (no Datejs):
Exmaple
var a = new Date(2011, 0, 1);
var b = a;
var c = b;
console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011
// setting only 'a' will cause 'b' and 'c' to update as well.
a.setDate(10);
console.log('a', a); // 10-Jan-2011
console.log('b', b); // 10-Jan-2011
console.log('c', c); // 10-Jan-2011
The way to work around this if using Datejs is by "cloning" the Date objects. The following sample demonstrates the use of the .clone()
function on the 'b' and 'c' Date objects.
Example
var a = new Date(2011, 0, 1);
var b = a.clone(); // clone creates a new 'copy' of 'a'.
var c = b.clone();
console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011
a.setDate(10);
console.log('a', a); // 10-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011
Running the above, you should see the final results of 'b' and 'c' still reflect their original values even though 'a' has changed.
Hope this helps.