tags:

views:

1163

answers:

2

How can I translate this pseudo code into working js [don't worry about where the end date comes from except that it's a valid javascript date].

var myEndDateTime = somedate;  //somedate is a valid js date  
var durationInMinutes = 100; //this can be any number of minutes from 1-7200 (5 days)

//this is the calculation I don't know how to do
var myStartDate = somedate - durationInMuntes;

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());
+8  A: 

Once you know this:

  • You can create a Date by calling the constructor with milliseconds since Jan 1, 1970.
  • The valueOf() a Date is the number of milliseconds since Jan 1, 1970
  • There are 60,000 milliseconds in a minute :-]

...it isn't so hard.

In the code below, a new Date is created by subtracting the appropriate number of milliseconds from myEndDateTime:

var MS_PER_MINUTE = 60000;
var myStartDate = new Date(myEndDateTime - durationInMinutes * MS_PER_MINUTE);
Daniel LeCheminant
Excellent detailed answer, thanks!
brendan
A: 

You can also use get and set minutes to achieve it:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

startdate.setMinutes(endDate.getMinutes() - durationInMinutes);
Miquel