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!
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With