Thursday, June 18, 2009

Cross-browser Javascript Datediff or Date difference function

Please visit my new Web Site

In javascript you don't get any straight cut way to calculate the date or time difference between two dates. But in our lives most of times 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. Don't be confused since the base is 1970 for all so that we can find out the milliseconds for both date. 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. So lets start to calculate the date difference between two given dates. Here i will show you an imporatant example:

1. Difference between a previous date to todate.

Difference between a previous date to todate:
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">
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)))

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 365 with msofaDay variable. Don't think about Leap year, you can beleive the built in methods.

Script tested for:
Internet Explorer
Mozilla Firefox
Google Chrome


Anonymous said...

It's like the DateDiff function I use normally ;)

Want to say something?

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash