How to get the day of the week from the day number in JavaScript?

后端 未结 8 1111
野的像风
野的像风 2020-12-03 07:05

Given dayNumber is from 0 - 6 representing Monday - Sunday respectively.

Can the Date /

8条回答
  •  离开以前
    2020-12-03 07:12

    The first solution is very straightforward since we just use getDay() to get the day of week, from 0 (Sunday) to 6 (Saturday).

    var dayOfTheWeek = (day, month, year) => {
      const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
      return weekday[new Date(`${month}/${day}/${year}`).getDay()];
    };
    
    console.log(dayOfTheWeek(3, 11, 2020));

    The second solution is toLocaleString() built-in method.

    var dayOfTheWeek = (day, month, year) => {
      return new Date(year, month - 1, day).toLocaleString("en-US", {
        weekday: "long",
      });
    };
    
    console.log(dayOfTheWeek(3, 11, 2020));

    The third solution is based on Zeller's congruence.

    function zeller(day, month, year) {
      const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
      if (month < 3) {
        month += 12;
        year--;
      }
      var h = (day + parseInt(((month + 1) * 26) / 10) +
        year + parseInt(year / 4) + 6 * parseInt(year / 100) +
        parseInt(year / 400) - 1) % 7;
      return weekday[h];
    }
    console.log(zeller(3, 11, 2020));

提交回复
热议问题