string 使用 JavaScript 从 Date 对象或日期字符串中获取工作日
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17964170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the weekday from a Date object or date string using JavaScript
提问by dpmzmdr
I have a date string in (yyyy-mm-dd) format, how can I get the weekday name from it?
我有一个 (yyyy-mm-dd) 格式的日期字符串,如何从中获取工作日名称?
Example:
例子:
- For the string "2013-07-31", the output would be "Wednesday"
- For today's date using
new Date()
, the output would be based on the current day of week
- 对于字符串“2013-07-31”,输出将是“Wednesday”
- 对于使用 的今天日期
new Date()
,输出将基于当前星期几
回答by Samuel Liew
Use this function, comes with date string validation:
使用这个函数,带有日期字符串验证:
If you include this function somewhere in your project,
如果您在项目中的某处包含此功能,
// 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];
}
You will be able to use it anywhere easily like this:
您将能够像这样轻松地在任何地方使用它:
getDayOfWeek( "2013-07-31" )
> "Wednesday"
getDayOfWeek( new Date() ) // or
getDayOfWeek( Date.now() )
> // (will return today's day. See demo jsfiddle below...)
If invalid date string is used, a null will be returned.
如果使用无效的日期字符串,将返回空值。
getDayOfWeek( "~invalid string~" );
> null
Valid date strings are based on the Date.parse() method as described in the MDN JavaScript reference.
有效的日期字符串基于Date.parse() 方法,如 MDN JavaScript 参考 中所述。
Demo:http://jsfiddle.net/samliew/fo1nnsgp/
演示:http : //jsfiddle.net/samliew/fo1nnsgp/
Of course you can also use the moment.jsplugin, especiallyif timezones are required.
当然你也可以使用moment.js插件,尤其是在需要时区的情况下。
回答by Code L?ver
Use below code:
使用以下代码:
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
回答by Black Mamba
Here are one-liner solutions but please check the support first.
这是单线解决方案,但请先检查支持。
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);
回答by achimt
If you do not want to write a function, just employ the user-defined format-code "NNNN". This will print the day of the week in the cell containing the date. If you really want string (rather than just having the word displayed in your spreadsheet) you can enter the formula
如果您不想编写函数,只需使用用户定义的格式代码“NNNN”。这将在包含日期的单元格中打印星期几。如果您真的想要字符串(而不仅仅是在电子表格中显示单词),您可以输入公式
=TEXT(A1;"NNNN")
resulting in a string containing the weekday.
产生一个包含工作日的字符串。