Cross-browser Javascript Datediff or Date Difference function Between Two Dates

In javascript you don’t get any straight cut method to calculate the date or time difference in Day between two dates. But most of the time we need 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 milliseconds by 1000 then we get second, if we divide by 60 then minute then we can calculate hour, day & year by dividing 365. So lets start to calculate the date difference between two given dates. Here i will show you an important example:

Difference between a Previous Date to To Date or Current Date:
To do that let the previous date is August 01, 2014 & the current date is August 07, 2014. So to get the Day difference, the script or code should be:

<script type="text/javascript">
    var toDate =new Date() //Today/current Date
    var prevDay=new Date("01 August 2014") //August 01, 2014

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

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

Sample Output:

Note: Today is the 7th day according to the above example. So if you use floor method then you will get 6 but for 7 you can use ceil method. If you want to get year difference then multiply msofaDay by 365. Don’t think about Leap year, you can trust the Javascript built in methods.

Script tested for:
1. Internet Explorer
2. Opera
3. Mozilla Firefox
4. Google Chrome

Download Code Example Javascript

Leave a Reply

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

AlphaOmega Captcha Classica  –  Enter Security Code