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.

Recommended Answers

All 2 Replies

Get the Unix time of both, and substract them, that's the diff in seconds.

Aeterna,

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.
//or
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.

Airshow

commented: Hey, that's nice, I didn't know you don't have to call getTime(). +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.