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

ryoqjall  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(77)

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

示例:

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

hc8w905p1#

使用此函数,自带日期字符串验证:

如果在项目中的某个地方包含此函数,

// 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

有效日期字符串基于Date.parse() method as described in the MDN JavaScript reference

Demo:http://jsfiddle.net/samliew/fo1nnsgp/

当然,你也可以使用moment.js插件,* 特别是 * 如果时区是必需的。

hgc7kmma

hgc7kmma2#

这里有一个线性的解决方案,但请先检查支持。

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)

Docs for Intl.DateTimeFormat object
Docs for localeDateString

jhkqcmku

jhkqcmku3#

使用下面的代码:

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

相关问题