>Javascript Comparing 2 dates
I have this code in comparing dates
var startDate = jQuery("#startDate_field_id").val();
var endDate = jQuery("#endDate_field_id").val();
var startDateSplit = startDate.split("-");
var endDateSplit = endDate.split("-");
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
if( end < start ) {
alert("End Date should be less than Start Date of the Event");
}
The value of #startDate_field_id is 2011-10-05
white the value of $endDate_field_id is 2011-10-04What do you think is the reason why this isn't working.
开发者_运维问答Any help would be greatly appreciated and rewarded. Thanks! :)
I think your first problem is that you are using the Date object incorrectly. You are passing three arguments to the setFullYear() method, which only takes a single argument, a 4 digit year.
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
You might want to try something like this:
var start = new Date(startDateSplit[0], startDateSplit[1] - 1, startDateSplit[2])
var end = new Date(endDateSplit[0], endDateSplit[1] - 1, endDateSplit[2]);
I'd use UNIX epoch timestamps for the comparison:
if (end.getTime() > start.getTime()) {
alert('...');
}
Because setFullYear method month parameter accept 0..11, means 9 is October.
why not use
var start = new Date(startDate);
var end = new Date(endDate);
var start = new Date(Number(startDateSplit[0]), Number(startDateSplit[1])-1, Number(startDateSplit[2]));
var end = new Date(Number(endDateSplit[0]), Number(endDateSplit[1])-1, Number(endDateSplit[2]));
or simply:
I am not sure I correctly understand your question .
I guess you want make sure that the end date must be greater than start date.
your code will work fine if you cahnge the if condition .And i just changed the alert message too to get proper meaning
Check this DEMO .
精彩评论