spamy spamy - 10 months ago 48
Javascript Question

Increment a var by one every 24 hours from a specific date

I've never used Javascript before (or any other programming language) so sorry for asking this question because im sure it's very simple.

What I want to do is set a date in Javascript, then increment it by one every 24 hours. So three days after the date is set, 3 is displayed in the HTML (not the date itself). And after 100 days, 100 is displayed.

Thank you.

Answer Source

You have to create two date objects, one representing your initial date, and another one representing right now. Then, calculate the difference:

// Calculate days since Dec 1st 2012
var initialDate = new Date(2012, 11, 1); // Attention: month is zero-based
var now =;
var difference = now - initialDate;
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var daysSince = Math.floor(difference / millisecondsPerDay);
alert(daysSince); // 80