我有一个 (yyyy-mm-dd) 格式的日期字符串,如何从中获取工作日名称?
示例:
new Date()
的今天日期,输出将基于当前星期几如果您在项目中的某个位置包含此功能,
// Accepts a Date object or date string that is recognized by the Date.parse() method
function getDayOfWeek(date) {
const dayOfWeek = new Date(date).getDay();
return isNaN(dayOfWeek) ? null :
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek];
}
您将能够像这样轻松地在任何地方使用它:
getDayOfWeek( "2013-07-31" )
> "Wednesday"
getDayOfWeek( new Date() ) // or
getDayOfWeek( Date.now() )
> // (will return today's day. See demo jsfiddle below...)
如果使用无效的日期字符串,将返回 null。
getDayOfWeek( "~invalid string~" );
> null
有效的日期字符串基于 MDN JavaScript 参考中描述的 Date.parse() 方法。
演示:http://jsfiddle.net/samliew/fo1nnsgp/
moment.js 插件,尤其是如果需要时区。
var gsDayNames = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
var d = new Date("2013-07-31");
var dayName = gsDayNames[d.getDay()];
//dayName will return the name of day
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let dates = [];
days.forEach((day,index)=>{
if(index == new Date().getDay()){
for(let i = index-1; i >= 0; i--) {
// console.log("days is "+day+" => "+(new Date().getDate() - i))
var date = new Date();
dates.push({date: new Date(date.setDate(date.getDate() - i)).toString(), days: days[i]+"-"+i})
}
var date = new Date();
dates.push({date: new Date(date.setDate(date.getDate())).toString(), days: days[index]+"-"+index})
// console.log("Today is "+day+" => "+new Date().getDate())
for(let i = index+1; i < days.length; i++) {
// console.log("day is "+day+" => "+(new Date().getDate() + i))
var date = new Date();
// add a day
dates.push({date: new Date(date.setDate(date.getDate() + i)).toString(), days: days[i]+"-"+i})
}
}
})
console.log(dates)