简体   繁体   中英

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.

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]); 

For date manipulation in javascript, there is this library :

http://www.datejs.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM