0

I'm trying to use the pattern described here: How to add number of days to today's date?

My goal is to start an animation at a date one week before a certain event, in this case the launch of Sputnik. My code is:

        var SputnikLaunchDate = new Date(1957, 9, 4); //The first event of insterest in the simulation.
        var earliestAnimationDate = new Date();
        earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7); //Start 1 week before then

When I do this in the Firefox debugger, the variable SputnikLauchDate is correct (1957-10-04T05:00:00.000Z). However, earliestAnimationDate ends up being 2015-05-28T18:49:54.313Z and I have no idea why. Can someone explain to me what I'm doing wrong?

Community
  • 1
  • 1
Nevo
  • 752
  • 2
  • 9
  • 22
  • This has already been discussed in this answer: http://stackoverflow.com/a/19691491/1665345 – NilsB Jun 14 '15 at 19:04

1 Answers1

1

The problem is that setDate sets the number of days relative to the current time, but when you constructed earliestAnimationDate you didn't give it any information, so it was set to today's date. Pass in SputnikLaunchDate.getTime() to initially copy that time into earliestAnimationDate (or else just put new Date(1957, 9, 4) again, of course).

var SputnikLaunchDate = new Date(1957, 9, 4);
var earliestAnimationDate = new Date(SputnikLaunchDate.getTime());
earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7);
alecmce
  • 1,456
  • 10
  • 23