我有一个 (yyyy-mm-dd) 格式的日期字符串,如何从中获取工作日名称?
示例:
- 对于字符串“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
有效的日期字符串基于 Date.parse() method as described in the MDN JavaScript reference .
演示: http://jsfiddle.net/samliew/fo1nnsgp/
当然你也可以使用moment.js插件,特别是如果需要时区。
关于javascript - 使用 JavaScript 从 Date 对象或日期字符串中获取工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17964170/