Javascript – Cross-browser Javascript Datediff or Date difference function

In javascript you don’t get any straight cut way to calculate the date or time difference between two dates.
But we need most of times to calculate the time difference between two dates.
Javascript gives us a built in function named getTime() which returns the number of milliseconds since midnight of January 1, 1970.

Now if we divide the millisecond by 1000 then we get second, if we divide by 60 then minute then hour then day & finally we get year by dividing 365.

To do that let the previous date is June 15, 2009 & the current date is June 21, 2009 so to get the day difference the script or code should be :


<script type="text/javascript">
var toDate =new Date() //June 21, 2009
var prevDay=new Date(2009, 5, 15) //June 15, 2009

//Get 1 day corresponding milliseconds
var msofaDay=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
document.write("Difference between two date is: "+Math.floor((toDate.getTime()-prevDay.getTime())/(msofaDay)))
</script>

<

One Reply to “Javascript – Cross-browser Javascript Datediff or Date difference function”

  1. Pingback: Javascript – Cross-browser Javascript Datediff or Date difference function

Leave a Reply

Your email address will not be published. Required fields are marked *

*