如何从Javascript中的日期编号获取星期几?

时间:2012-03-13 02:51:27

标签: javascript string date

鉴于dayNumber来自0..6,分别代表Monday..Sunday

可以使用Date / String个对象从dayNumber获取星期几吗?

10 个答案:

答案 0 :(得分:46)

一种更优雅的方式,如果您选择启用最新版本的ECMA脚本并且在所有最新浏览器和node.js中运行,您还可以通过区域设置显示工作日:

console.log(new Date().toLocaleString('en-us', {  weekday: 'long' }));

答案 1 :(得分:29)

这将根据您传递的索引给您一天的时间:

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

输出“今天是星期四”

您可以使用getDay()从JavaScript获取当前天数索引(但是在此方法中,星期日为0,星期一为1,等等):

var d=new Date();
console.log(d.getDay());

星期一输出1。

答案 2 :(得分:20)

此代码是上面给出的修改版本。它返回表示日期的字符串

/**
* Converts a day number to a string.
*
* @param {Number} dayIndex
* @return {String} Returns day as string
*/
function dayOfWeekAsString(dayIndex) {
  return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][dayIndex];
}

例如

dayOfWeekAsString(0) returns "Monday"

答案 3 :(得分:6)

这会将getDayOfWeek()函数添加为JavaScript Date类的原型。

Date.prototype.getDayOfWeek = function(){   
    return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][ this.getDay() ];
};

答案 4 :(得分:3)

/**
* I convert a day string to an number.
*
* @method dayOfWeekAsInteger
* @param {String} day
* @return {Number} Returns day as number
*/
function dayOfWeekAsInteger(day) {
  return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"].indexOf(day);
}

答案 5 :(得分:1)

let weekday = ['Sunday',
               'Monday',
               'Tuesday',
               'Wednesday',
               'Thursday',
               'Friday',
               'Saturday'][new Date().getDay()];

console.log(weekday)

答案 6 :(得分:0)

email

答案 7 :(得分:0)

第一个解决方案非常简单,因为我们只使用getDay()来获取星期几,从0(星期日)到6(星期六)。

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

第二种解决方案是toLocaleString()内置方法。

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

console.log(dayOfTheWeek(3, 11, 2020));

第三个解决方案基于 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));

答案 8 :(得分:0)

只需使用库 moment

const moment = require('moment')
console.log(moment(person.dateOfBirth,'DD.MM.YYYY').format("dddd {d}"))

输出:

Monday {1}

答案 9 :(得分:0)

如果需要,可以通过使用带有选项参数的 sudo 获得一天的全名(例如“星期一”)。

Intl.DateTimeFormat