Reputation: 21
I want to check if a date occurs between two dates. If this date occurs between these two dates the function should return true, otherwise it should return false.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
function dateCheck() {
var fDate,lDate,cDate;
fDate = jQuery.datepicker.formatDate('dd-mm-yy', new Date()); // firstdate
cDate = jQuery.datepicker.parseDate('dd-mm-yy',
jQuery('#challenge_date').val()); // date from form
lDate = jQuery.datepicker.formatDate('dd-mm-yy', new Date());
lDate.setDate(lDate.getDate() + 7); // lastdate
if((cDate <= lDate && cDate >= fDate)) {
alert("true");
return true;
}
alert("false");
return false;
}
</script>
<form action="#" method="post" onsubmit="return dateCheck()">
<input type="date" name="challenge_date" id="challenge_date">
<input type="submit" value="check">
</form>
Can anyone point out my mistake of give me a push in the right direction?
Upvotes: 1
Views: 9537
Reputation: 719
You are using html native date input type. Therefore no need is there to use jQuery datepicker API. Simply create date object from the input value and compare with other Date objects.
function dateCheck() {
var fDate,lDate,cDate;
fDate = new Date(); // firstdate
cDate = new Date($('#challenge_date').val()); // date from form
lDate = new Date();
lDate.setDate(lDate.getDate() + 7); // lastdate
if(Date.parse(cDate) <= Date.parse(lDate) && Date.parse(cDate) >= Date.parse(fDate)){
alert("true");
return true;
}
alert("false");
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" onsubmit="return dateCheck()">
<input type="date" name="challenge_date" id="challenge_date">
<input type="submit" value="check">
</form>
Upvotes: 2
Reputation: 764
Date function does not support dd/mm/yyyy. So try this
function dateCheck() {
var fDate,lDate,cDate;
fDate = jQuery.datepicker.formatDate('dd-mm-yy', new Date()); // firstdate
cDate = jQuery.datepicker.parseDate('dd-mm-yy', jQuery('#challenge_date').val()); // date from form
lDate = jQuery.datepicker.formatDate('dd-mm-yy', new Date());
var dateFrom = fDate.split("-");
var dateTo = lDate.split("-");
var dateCheck = cDate.split("-");
var from = new Date(dateFrom[2], parseInt(dateFrom[1])-1, dateFrom[0]); // -1 because months are from 0 to 11
var to = new Date(dateTo[2], parseInt(dateTo[1])-1, dateTo[0]);
var check = new Date(dateCheck[2], parseInt(dateCheck[1])-1, dateCheck[0]);
if((check <= to && check >= from)) {
alert("true");
return true;
}
alert("false");
return false;
}
Upvotes: 0