使用 JavaScript 从 Date 对象或日期字符串获取工作日

问题描述 投票:0回答:4

我有一个 (yyyy-mm-dd) 格式的日期字符串,如何从中获取工作日名称?

示例:

  • 对于字符串“2013-07-31”,输出将为“Wednesday”
  • 对于使用
    new Date()
    的今天日期,输出将基于当前星期几
javascript string function date dayofweek
4个回答
37
投票

使用此功能,自带日期字符串验证:

如果您在项目中的某个位置包含此功能,

// 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 插件,尤其是如果需要时区。


15
投票
以下是单行解决方案,但请先检查支持情况。

let current = new Date(); let today = current.toLocaleDateString('en-US',{weekday: 'long'}); console.log(today); let today2 = new Intl.DateTimeFormat('en-US', {weekday: 'long'}).format(current); console.log(today2)

Intl.DateTimeFormat 对象的文档

localeDateString 文档


12
投票
使用以下代码:

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
    

0
投票
查找当天的所有工作日。

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)
    
© www.soinside.com 2019 - 2024. All rights reserved.