最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript date function returns wrong day of the week - Stack Overflow

programmeradmin2浏览0评论

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 pletely having to redo my code?

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

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 pletely having to redo my code?

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

Share Improve this question asked Jan 30, 2016 at 23:43 Cody CarmichaelCody Carmichael 1873 silver badges16 bronze badges 3
  • 4 kindly consider reading the documentation – njzk2 Commented Jan 30, 2016 at 23:48
  • Make sure you use parseInt(Val, 10), otherwise values like 08 and 09 will be parsed as if they were base-8. Also, Date constructor takes year-month-day, not month-day-year. – Krease Commented Jan 30, 2016 at 23:51
  • @Chris—parseInt isn't required at all. Where more than one value is supplied to the Date constructor, they are converted to number anyway. – RobG Commented Feb 1, 2016 at 2:52
Add a ment  | 

4 Answers 4

Reset to default 5

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])
    );

Why not use Moment.js?

Take a look at this code example:

var date = moment("2016-01-31");
var weekDayNumber = date.day(); // Return the number of dayweek (0 in this case)
if (weekDayNumber === 0){console.log("Born Sunday");}
else if(weekDayNumber === 1){console.log("Born Monday");}

The fact that the code reports the correct weekday for some dates is just a coincidence. You are using the month as year, the day as month and the year as day.

Swap the values around so that you get the year, month, day order that the Date constructor expects:

var userDate = new Date(
    parseInt(birthdayArray[2], 10),
    parseInt(birthdayArray[0], 10)-1,
    parseInt(birthdayArray[1], 10)
);

Also, the parseInt takes a second parameter that is the base, which is especially important to specify when you are parsing values with a leading zero, as they are interpreted as base 8 by default.

Since you've already validated the user entered the date in the form MM-DD-YYYY, you could change this

var userDate = new Date(
    parseInt(birthdayArray[0])-1,
    parseInt(birthdayArray[1])-2,
    parseInt(birthdayArray[2])
);

to this

var userDate = new Date(birthday);

Test code:

var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday'];
var d = new Date("04-04-1994");
document.writeln("DATE: " + d + "<br>");
document.writeln("DAY OF THE WEEK: " + d.getDay() + "<br>");
var dayName = weekDays[d.getDay()];
document.write("You were born on "+dayName);

Disclaimer: Only works in browsers expecting the date format to be MM-DD-YYYY

发布评论

评论列表(0)

  1. 暂无评论