Reputation: 187
I would like a simple text box input of a date in the past and then for it to display how many days it is from today's date. I have found several examples of how to use javascript to do it between two dates that you input, but not with only doing one date and today's.
The current date to track is 4/2/2010, but it will change over time.
Upvotes: 2
Views: 11969
Reputation: 306
Here is a script I use for countdown timers. You can take out whatever parts you dont need to display just a day, time etc.
dateFuture = new Date(2029,2,4,23,59,59);
function GetCount(){
dateNow = new Date();
//grab current date
amount = dateFuture.getTime() - dateNow.getTime();
//calc milliseconds between dates
delete dateNow;
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Now!";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" day"+((days!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0){out += hours +" hour"+((hours!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+",<br />";}
out += secs +" seconds";
document.getElementById('countbox').innerHTML=out;
setTimeout("GetCount()", 1000);
}
}
window.onload=function(){GetCount();}//call when everything has loaded
<div id="countbox"><div>
Upvotes: 1
Reputation: 154818
If you don't care about the leap second (:)
), you can simply subtract the current date from the date back then, which gets you the difference in milliseconds, and then divide the difference by the amount of milliseconds that fits in one day:
var then = new Date(2010, 03, 02), // month is zero based
now = new Date; // no arguments -> current date
// 24 hours, 60 minutes, 60 seconds, 1000 milliseconds
Math.round((now - then) / (1000 * 60 * 60 * 24)); // round the amount of days
// result: 712
Upvotes: 1