Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of days between two dates with javascript

I get a date from a datetime picker with this:

var endDate = new Date();
endDate = $("input[id$='DateTimeControl2Date']").val()

Then I find another date and try to check how many days there are between these two dates but I get the error "Object doesn't support this property or method". What am I doing wrong?

$('.StatusDateTable').each(function() {
var statusDate = new Date(); 
statusDate = $(this).find(".dates").html();
var statusLight = $(this).find(".StatusLight").attr("src");
statusLight = statusLight.substring(33).slice(0,-9);
if (statusLight == "Blue") {
var oneDay = 1000*60*60*24;

alert(endDate + statusDate);
var date1_ms = endDate.getTime();
var date2_ms = statusDate.getTime();

var dayDifference = Math.abs(Math.round((date1_ms - date2_ms)/oneDay));

alert(dayDifference);

}
});

endDate has the format of 02/09/2010 and statusDate 1/09/2010.

Thanks in advance.

like image 618
Peter Avatar asked Feb 02 '26 14:02

Peter


1 Answers

Date() is a constructor function, when you call it you're assigning the result of that constructor to a variable. Then, in the line afterwards you're assigning a different object, the result of the jQuery val() method, to the same variable.

// The next line will overwrite the current value of `endDate`
endDate = $("input[id$='DateTimeControl2Date']").val()

Date() accepts an argument that will be parsed as the date. This is how you correctly set a new date object to a specific date/time:

var endDate = new Date($("input[id$='DateTimeControl2Date']").val());

This assumes that the date is returned in a format that Date() can parse. The same applies to your statusDate variable.


Just seen the format of the two dates at the bottom, which won't work well when being parsed by Date(). They won't parse at all in IE, and other browsers parse them as if they were mm/dd/yyyy format. This means you will have to manually split them and apply them to the Date() constructor:
var endDateSplit = $("input[id$='DateTimeControl2Date']").val().split("/"),
    endDate = new Date(endDateSplit[2], endDateSplit[1]-1, endDateSplit[0]);
like image 163
Andy E Avatar answered Feb 05 '26 07:02

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!