Reputation: 2460
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!
Upvotes: 4
Views: 137
Reputation: 7359
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.
Upvotes: 2
Reputation: 22031
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]);
Upvotes: 5