mardi 29 décembre 2020

What if if statement is not executed and does not recognize numerical data from the date format?

A user suppose to enter the date and based on the date entered the code determines which day of the week was at that specific date?

The code successfully recognize the day of the week and recognize that each month has 31 days, so if I enter February 31, it automatically recognizes as March 3 if the year is simple, and as March 2 if the year is leap! If I enter some gibberish let's say 2019-15-34 it returns as NaN!

I set up conditions for each month that if the month is January maximal number of days should not surpass 31, and if the month is February maximal number of days should not surpass 28 if the year is simple, and so on for each month. After that I set up alert to show the message "Your data is invalid! Please enter valid data!" and set up continue thereafter to return eventual user to reenter the data this time valid date. If date is valid (the month is not suppose to be greater than 12, and date suppose not to be greater than 31) it suppose to show up the message "OK!Your data is valid!" and the code to continue with execution and to get out of if statement!

However it's evident that even when I enter some date that does not make sense let's say 2019-15-15 the code does not return "Your data is invalid! Please enter valid data!", but no matter of what I enter it comes out "OK! Your date is valid!".

What's wrong and why if statement does not recognize date and month format and does not properly execute the code?

Here is the code:

var flag = false;
while(!flag){
    var anydate = prompt('Enter any date in format yyyy-mm-dd', anydate);
    anydate = new Date(anydate);
    var dd = anydate.getDate();
    var mm = (anydate.getMonth()+1);
    var yyyy = anydate.getFullYear();
    if(((mm<1)||(mm>12)||((mm===1)&&(dd>31))||((mm===2)&&(dd>28))||((mm===3)&&(dd>31))|| ((mm===4)&&(dd>30))||((mm===5)&&(dd>31))||((mm===6)&&(dd>30))||((mm===7)&&(dd>31))||((mm===8)&&(dd>31))||((mm===9)&&(dd>30))||((mm===10)&&(dd>31))||((mm===11)&&(mm>30))||((mm===12)&&(dd>31)))){
        alert('Your data is invalid! Enter valid date please!');
        continue;
        flag = false}else{
        alert('OK! You can continue with process!');
        break;
    };
};

var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

console.log(weekday[anydate.getDay()]);
console.log(anydate.getMonth()+1);
console.log(anydate.getDate());
console.log(anydate.getFullYear());
a = anydate
anydate = mm + '-' + dd + '-' + yyyy;
console.log(anydate);

Aucun commentaire:

Enregistrer un commentaire