Reputation: 59
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);
}
Upvotes: 0
Views: 1135
Reputation: 66921
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)
}
Upvotes: 3
Reputation: 324610
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.
Upvotes: 0
Reputation: 109232
Remove the quotes around startdate
in the call to Date.parse
. And the Date.
in front of your variable names in the calculation.
Upvotes: 1