Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calculating diference between to dates

Status
Not open for further replies.

jazzmaster111

Programmer
May 2, 2005
25
MX
Hi!

I'm trying to calculate the number of days between to dates, I have downloaded an example of a web page.


I think the function is right but if I want to calculate the number of days between 2005/2/28 and 2005/3/1 it returns 4.

If I want to calculate the number of days between 2005/11/30 and 2005/12/1 it returns 2.

What could be wrong??

Thanks!!

This is the code

<script language="JavaScript" type="text/javascript">
<!--

function days_between(date1, date2) {

// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24

// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()

// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)

// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)

}

//-->
</script>
 

Do the date objects definately hold the right dates? Try alerting date1 and date2 at the start of the function, and ensure that they look right.

Dan


[tt]D'ya think I got where I am today because I dress like Peter Pan here?[/tt]
[banghead]

 
jazzmaster111,

js date object's month is zero-based if you establish it with new Date where you might think it is most user-friendly. It's crazy, is it not?
[tt] date1=new Date(2005,2,28)
date2=new Date(2005,3,1)[/tt]
Contrary to what you might think, it measn 28 Mar 2005 and 1 Apr 2005. Hence the result 4. And then
[tt] date1=new Date(2005,11,30)
date2=new Date(2005,12,1)[/tt]
You get 30 Dec 2005 and 1 Jan 2006 (automatically). Hence the result 2.

regards - tsuji
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top