开发者

How can I count the days between two dates in javascript? [duplicate]

开发者 https://www.devze.com 2023-04-08 22:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to calculate the number of days between two dates using javascript
This question already has answers here: Closed 11 years ago.

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?)?


var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);


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


// 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消