0

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);
    }
labman
  • 59
  • 1
  • 9

3 Answers3

3

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)

}
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
1

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

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
0

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • if i'm collecting a date from a form field like this: var startdate = document.forms[0].datescopestart.value; The format returned is dd/mm/yyyy i.e 23/07/2012 How do I turn it into a vaild date oject? – labman Jul 23 '12 at 21:12