Calculate the Days Since a Given Date (Javascript)
I recently needed to calculate the number of days that had elapsed since a given date. Not happy with any of the code snippets I found on the internet, I wrote my own. A demo is below, along with the the javascript code. Note that the code uses a bit of dynamic HTML so no page refresh is necessary. The answer will appear beneath the form.
Feel free to use these in your projects.
Demo – Calculate the number of days since a given date
To get this to work on your website, you’ll need the following javascript function, along with the HTML file below.
The JavaScript:
function daysSince(m,d,y){
if (d == '' || m=='' || y==''){
alert ("All fields must be entered");
return;
}
if (isNaN(m) || isNaN(y) || isNaN(d)){
alert("Only numbers .");
return;
}
var myDate=new Date();
var yourDate=new Date(y,m-1,d);
var secondsInADay = 1000*60*60*24;
var diff = Math.floor( (myDate.getTime() - yourDate.getTime()) / secondsInADay );
document.getElementById("result").innerHTML= "It has been " +
diff + " days since " + m + "/" + d + "/" + y +".";
}
The HTML:
If you make any useful alterations, feel free to share them in the comments.


Leave a Reply