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

dpm*_*mdr 16 javascript string date function dayofweek

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

例:

  • 对于字符串"2013-07-31",输出将是"星期三"
  • 对于今天的使用日期new Date(),输出将基于当前的星期几

Sam*_*iew 20

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

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

// Accepts a Date object or date string that is recognized by the Date.parse() method
function getDayOfWeek(date) {
  var dayOfWeek = new Date(date).getDay();    
  return isNaN(dayOfWeek) ? null : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek];
}
Run Code Online (Sandbox Code Playgroud)

您可以在任何地方轻松使用它,如下所示:

getDayOfWeek("2013-07-31")
> "Wednesday"

getDayOfWeek(new Date())
> // (will return today's day. See demo jsfiddle below...)
Run Code Online (Sandbox Code Playgroud)

如果使用无效的日期字符串,则返回null.

getDayOfWeek("~invalid~");
> null
Run Code Online (Sandbox Code Playgroud)

有效的日期字符串基于MDN JavaScript参考中描述Date.parse()方法.

演示: http ://jsfiddle.net/samliew/fo1nnsgp/


当然你也可以使用moment.js插件,特别是如果涉及时区的话.


Cod*_*ver 6

使用以下代码:

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
Run Code Online (Sandbox Code Playgroud)


Bla*_*mba 5

这里是单线解决方案,但请先检查支持。

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);
Run Code Online (Sandbox Code Playgroud)

Intl.DateTimeFormat对象的文档

适用于localeDateString的文档