我正在从服务器检索时间戳,如下所示:
2016-03-08 15:30
我有一个数组可以传入以获取星期几:
var dayNameArray = {
"0": "Sun",
"1": "Mon",
"2": "Tue",
"3": "Wed",
"4": "Thu",
"5": "Fri",
"6": "Sat"
}
我如何才能说明一周的哪一天?谢谢!
答案 0 :(得分:5)
从字符串构造日期并使用getDay方法获取日期编号:
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]);
答案 1 :(得分:1)
简短版本:
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);

当前构造使用split
方法,该方法比常规数组短:
'Sun Mon Tue Wed Thu Fri Sat'.split(' ')
['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
我的建议是将所有-
替换为/
,以便与更多浏览器兼容。有关详细信息,请参阅"Why new Date()
is always return null
?"问题和解答。