-2

Possible Duplicate:
How to calculate the number of days between two dates using javascript

I have those dates :

27/09/2011
29/10/2011

and I'd like to return the days between those dates (in the example, should be 33 days).

How can I do it on javascript (or jquery?)?

Community
  • 1
  • 1
markzzz
  • 47,390
  • 120
  • 299
  • 507

3 Answers3

4
var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
2
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)

}

http://www.mcfedries.com/JavaScript/DaysBetween.asp

BNL
  • 7,085
  • 4
  • 27
  • 32
0
// split the date into days, months, years array
var x = "27/09/2011".split('/')
var y = "29/10/2011".split('/')

// create date objects using year, month, day
var a = new Date(x[2],x[1],x[0])
var b = new Date(y[2],y[1],y[0])

// calculate difference between dayes
var c = ( b - a )

// convert from milliseconds to days
// multiply milliseconds * seconds * minutes * hours
var d = c / (1000 * 60 * 60 * 24)

// show what you got
alert( d )

Note: I find this method safer than Date.parse() as you explicitly specify the date format being input (by splitting into year, month, day in the beginning). This is important to avoid ambiguity when 03/04/2008 could be 3rd of April, 2008 or 4th of March, 2008 depending what country your dates are coming from.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Billy Moon
  • 57,113
  • 24
  • 136
  • 237