Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get day of week from returned date from server

Tags:

javascript

I'm retrieving a timestamp from a server as follows:

2016-03-08 15:30

I have an array to pass in to get the day of the week:

var dayNameArray = {
"0": "Sun",
"1": "Mon",
"2": "Tue",
"3": "Wed",
"4": "Thu",
"5": "Fri",
"6": "Sat"
}

How would I get this to say what the day of the week is? Thanks!

like image 250
Kody R. Avatar asked Mar 14 '23 01:03

Kody R.


2 Answers

Construct Date from string and use getDay method to get day number:

var myDate = new Date("2016-03-08 15:30");
var dayNum = myDate.getDay();

var dayNameArray = {
  "0": "Sun",
  "1": "Mon",
  "2": "Tue",
  "3": "Wed",
  "4": "Thu",
  "5": "Fri",
  "6": "Sat"
}
console.log(dayNameArray[dayNum]);
like image 59
Andriy Ivaneyko Avatar answered Mar 18 '23 21:03

Andriy Ivaneyko


A short version:

var date = new Date('2016-03-08 15:30'.replace(/\-/g, '/'));
var day = 'Sun Mon Tue Wed Thu Fri Sat'.split(' ')[date.getDay()];

console.log(day);

The current construction uses the split method, which is shorter than the regular array:

'Sun Mon Tue Wed Thu Fri Sat'.split(' ')
['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

My suggestion is to replace all - with / for compatibility with more browsers. For more details please see "Why new Date() is always return null?" question and answers.

like image 39
Valentin Podkamennyi Avatar answered Mar 18 '23 21:03

Valentin Podkamennyi