In my code when i
equals 5 myDate
should be equal to it. The alert shows me that they are the same. I can never get the function to return 1;
function checkForHoliday(date) {
var myDate = new Date(date);
myDate = myDate.getMonth() + "/" + myDate.getDate() + "/" + myDate.getFullYear();
alert(myDate + "\n" + holidays[5]);
for (i = 0; i <= 9; i++) {
if (myDate == holidays[i]) {
return 1;
alert("got it");
}
}
return 0;
}
This is what the string in the array looks like:
year = 2013
holidays[5] = "7/2/" + year
My alert shows me this:
I have run your code locally, and have it working.
I'm going to guess that your issue stems from the fact that Date.getMonth() returns month numbers where January === 0. That throws a lot of people off.
To recreate your code, I simply used Chrome's console. I also changed your alert to a console.log
to save myself the hassle of using alert
.
Here's the code:
function checkForHoliday(date) {
var myDate = new Date(date);
myDate = myDate.getMonth() + "/" + myDate.getDate() + "/" + myDate.getFullYear();
console.log(myDate + "\n" + holidays[5]);
for (i = 0; i <= 9; i++) {
if (myDate == holidays[i]) {
return 1;
}
}
return 0;
}
And a fake holiday array:
holidays = [0,1,2,3,4,'7/2/2013']
(The 7 here actually corresponds to August)
Upon running checkForHoliday('8/2/2013')
, the console reports back a response of 1
. The code successfully matches the date.
If you actually intended for holiday[5]
to represent July 2nd, 2013, you'll need to set holiday[5] = '6/2/2013'
.
Try Using this,
<script type="text/javascript">
var startYear = parseInt(document.getElementById('startYear'), 10);
var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1;
var startDay = parseInt(document.getElementById('startDay'), 10);
var myDate = new Date(startYear, startMonth, startDay);
</script>
Convert the date object to string in desired format. Use triple equals operator to test equality.
Try:
if (myDate.toLocaleDateString() === holidays[i]) {
return 1;
alert("got it");
}
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.