给定的分别dayNumber
来自0
-6
代表Monday
- Sunday
。
可以使用Date
/String
对象来获取星期几dayNumber
吗?
给定的分别dayNumber
来自0
-6
代表Monday
- Sunday
。
可以使用Date
/String
对象来获取星期几dayNumber
吗?
一种更优雅的方式,如果您选择,还可以按区域设置显示工作日,可用于启动最新版本的 ECMA 脚本,并在所有最新浏览器和 node.js 中运行:
console.log(new Date().toLocaleString('en-us', { weekday: 'long' }));
这将根据您通过的索引为您提供一天:
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]);
输出“今天是星期四”
您还可以使用 JavaScript 获取当前天数索引getDay()
(但是在此方法中,星期日为 0,星期一为 1 等):
var d=new Date();
console.log(d.getDay());
星期一时输出 1。
此代码是上面给出的修改版本。它返回代表日期的字符串
/**
* Converts a day number to a string.
*
* @param {Number} dayIndex
* @return {String} Returns day as string
*/
function dayOfWeekAsString(dayIndex) {
return ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][dayIndex] || '';
}
例如
dayOfWeekAsString(0) returns "Sunday"
/**
* 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);
}
这将向 JavaScript Date 类添加一个 getDayOfWeek() 函数作为原型。
Date.prototype.getDayOfWeek = function(){
return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][ this.getDay() ];
};