开发者

Count number of days between two dates with javascript

开发者 https://www.devze.com 2023-01-14 13:17 出处:网络
I get a date from a datetime picker with this: var endDate = new Date(); endDate = $(\"input[id$=\'DateTimeControl2Date\']\").val()

I get a date from a datetime picker with this:

var endDate = new Date();
endDate = $("input[id$='DateTimeControl2Date']").val()
开发者_StackOverflow中文版

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号