Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date function returns wrong day of the week

My Javascript function works, but reports the wrong day of the week. Some days it works but some don't. For instance January 22nd, 1991 reports correctly as Tuesday but April 04, 1994 reports incorrectly. How is this fixed?

Also how do I implement a condition that returns "You're from the future?!" if the user provides a future date.

Here is my function so far.

    //ask user for birthday
var birthday = window.prompt("What is your birthday? (MM-DD-YYYY)", "");
var birthdayArray = birthday.split('-');
//validate entry is correct
if(birthdayArray.length !==3){
    alert("invalid date")
}
//validate if date format is correct
else{
     if(!birthdayArray[0].match(/^\d\d$/) ||
       !birthdayArray[1].match(/^\d\d$/) ||
       !birthdayArray[2].match(/^\d\d\d\d$/)){
        alert("invalid date");
     }
///take user input and find weekday
     else{var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday'];
    var userDate = new Date(
        parseInt(birthdayArray[0])-1,
        parseInt(birthdayArray[1])-2,
        parseInt(birthdayArray[2])
    );
    var result = userDate.getDay();
    var dayName = weekDays[result];
    document.write("You were born on "+dayName);
}
}

Can this be done without completely having to redo my code?

EDIT: The -1 and -2 were me toying around with date fixes hoping I could find a golden combination, so far nothing.

like image 219
Cody Carmichael Avatar asked Jul 18 '26 01:07

Cody Carmichael


1 Answers

Because it's backwards. Date constructor looks like-

new Date(year, month, day);

You are doing-

new Date(month, day, year);

So it should instead be-

var userDate = new Date(
        parseInt(birthdayArray[2]),
        parseInt(birthdayArray[0])-1, // dates in javascript start counting at 0
        parseInt(birthdayArray[1])
    );
like image 57
micah Avatar answered Jul 19 '26 13:07

micah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!