可能重复:
How to calculate the number of days between two dates using javascript
我有那些日期:
27/09/2011
29/10/2011
我希望返回这些日期之间的日期(例如,应该是33天)。
我怎么能在javascript(或jquery?)上做到这一点?
答案 0 :(得分:4)
var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);
答案 1 :(得分: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)
}
答案 2 :(得分: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 )
注意:
我发现这种方法比Date.parse()
更安全,因为你明确指定了输入的日期格式(通过在开头分成年,月,日)。根据您的日期来自哪个国家/地区,03/04/2008
可能3rd of April, 2008
或4th of March, 2008
,这对于避免歧义非常重要。