Get the weekday from a Date object or date string using JavaScript

依然范特西╮ 提交于 2020-01-09 02:21:06

问题


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

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

回答1:


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) {
  var 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())
> // (will return today's day. See demo jsfiddle below...)

If invalid date string is used, a null will be returned.

getDayOfWeek("~invalid~");
> null

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

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


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




回答2:


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



回答3:


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);

Docs for Intl.DateTimeFormat object

Docs for localeDateString



来源:https://stackoverflow.com/questions/17964170/get-the-weekday-from-a-date-object-or-date-string-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!