可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.