calculate days between dates

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I'm trying to calculate the days between 2 dates but just keep getting "NaN. I've looked at other posts but can't quite work it out :-S

function checkdate() {  var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var datenow = (day + "/" + month + "/" + year)     var startdate = document.forms[0].datescopestart.value; var sDate = new Date(Date.parse("startdate","dd/mm/yy"));  var totaldays = Date.datenow - Date.sDate;       alert(totaldays);     } 

回答1:

Here's the function I've had in my library for a while now, works great.

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:

Remove the quotes around startdate in the call to Date.parse. And the Date. in front of your variable names in the calculation.



回答3:

The easiest way to do this is as follows:

var days = Math.floor(enddate.getTime()-startdate.getTime())/(24*60*60*1000); 

Where startdate and enddate are valid Date objects.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!