我有一个 (yyyy-mm-dd) 格式的日期字符串,如何从中获取工作日名称?
Example:
- 对于字符串“2013-07-31”,输出将为“Wednesday”
- 对于今天的日期,使用
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() 方法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse.
Demo: http://jsfiddle.net/samliew/fo1nnsgp/ http://jsfiddle.net/samliew/fo1nnsgp/
当然你也可以使用moment.js https://momentjs.com插入,尤其如果需要时区。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)