I'm trying to use JavaScript to loop through a json file which has time periods (starting date/time and ending date/time), and check if now (current date time) falls between any time period in such list.
Following is my code, but can't get where I'm wrong. Any help?
<html>
<script type="text/javascript">
var data = {
"period": {
"startend": [{
"startDate": "2015-11-17 15:43:37",
"endDate": "2015-11-18 19:43:37"
}, {
"startDate": "2015-12-17 19:43:37",
"endDate": "2016-01-17 19:43:37"
}, {
"startDate": "2015-04-17 19:43:37",
"endDate": "2015-04-18 19:43:37"
}]
}
}
var periodArray = data.period.startend;
var curDate = new Date();
var datetime = curDate.getFullYear() + '-' + curDate.getMonth() + '-' + curDate.getDate() + ' ' + curDate.getHours() + ':' + curDate.getMinutes() + ':' + curDate.getSeconds();
for (i = 0; i < periodArray.length ; i++) {
var obj = periodArray[i]
if (datetime > obj.startDate && datetime < obj.endDate){
alert('Falls within period');
} else {
alert('Not within any period');
}
}
</script>
obj.startDateis just a String. Might want to donew Date(obj.startDate)and so on to get actual dates out of the strings. Then, presumably the comparison between dates will work.