使用 JavaScript 从 Date 对象或日期字符串中获取工作日 [英] Get the weekday from a Date object or date string using JavaScript

查看:62
本文介绍了使用 JavaScript 从 Date 对象或日期字符串中获取工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a date string in (yyyy-mm-dd) format, how can I get the weekday name from it?

示例:

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

推荐答案

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

如果您在项目中的某处包含此功能,

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

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

Valid date strings are based on the Date.parse() method as described in the MDN JavaScript reference.

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

当然,您也可以使用 moment.js 插件,特别是如果需要时区.

Of course you can also use the moment.js plugin, especially if timezones are required.

这篇关于使用 JavaScript 从 Date 对象或日期字符串中获取工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆