I'm writing a little script thats a countdown timer.

What i want to do is be able to set a length of time like 3, 5, 7 days etc.

So i will have

var dif = 3;
var now = new Date();
var end = new Date(now.getFullYear(), now.getMonth(), now.getDay() + dif);

So my question is how do I find how many seconds make up the difference between the two dates and then how do I count down from now to the end time.

6 Years
Discussion Span
Last Post by Airshow


The javascript Date object is essentially a variable representing a number of milliseconds since midnight 1 January 1970, plus a raft of methods for setting and getting this value in a variety of formats.

Date subtraction is very simple.

var difference = date2 - date1;//where date2 and date1 are instances of the Date object.
var difference = end - new Date();//gives the time to go from now to a previously established end date.
// In both cases, difference is in milliseconds.

Then do some trivial math to convert milliseconds into days:hours:mins:seconds:milliseconds as required.


Edited by Airshow: n/a

Votes + Comments
Hey, that's nice, I didn't know you don't have to call getTime().
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.