Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the day of the week from the day number in JavaScript?

Given dayNumber is from 0 - 6 representing Monday - Sunday respectively.

Can the Date / String objects be used to get the day of the week from dayNumber?

like image 506
Misha Moroshko Avatar asked Mar 13 '12 02:03

Misha Moroshko


People also ask

How do I get the day of the week in JavaScript?

getDay() The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

How do you find the day of the week from a Date object?

The getDay() method returns the day of the week (0 to 6) of a date.


Video Answer


2 Answers

A much more elegant way which allows you to also show the weekday by locale if you choose to is available starting the latest version of ECMA scripts and is running in all latest browsers and node.js:

console.log(new Date().toLocaleString('en-us', {  weekday: 'long' }));
like image 108
Gabriel Kohen Avatar answered Sep 19 '22 15:09

Gabriel Kohen


This will give you a day based on the index you pass:

var weekday=new Array(7); weekday[0]="Monday"; weekday[1]="Tuesday"; weekday[2]="Wednesday"; weekday[3]="Thursday"; weekday[4]="Friday"; weekday[5]="Saturday"; weekday[6]="Sunday"; console.log("Today is " + weekday[3]); 

Outputs "Today is Thursday"

You can alse get the current days index from JavaScript with getDay() (however in this method, Sunday is 0, Monday is 1, etc.):

var d=new Date(); console.log(d.getDay()); 

Outputs 1 when it's Monday.

like image 26
j08691 Avatar answered Sep 16 '22 15:09

j08691