views:

408

answers:

3

I used the following function,

function datediff()
{
 var dat1 = document.getElementById('date1').value;
 alert(dat1);//i get 2010-04-01
var dat2 = document.getElementById('date2').value;
 alert(dat2);// i get 2010-04-13

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay));
alert(diffDays);
}

i get the error dat1.getTime() is not a function....

+1  A: 

you nead instance of class Date , to use this function/method .

This method is always used in conjunction with a Date object.

like :

var d = new Date();
d.getTime();

link :

http://www.w3schools.com/jsref/jsref_getTime.asp

Haim Evgi
+1  A: 

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

CMS
A: 

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);
Ryan Doherty