JS中把时间转换成星期几
方法一:比较土
JavaScript中通过日期得到星期几的方法:
1、可以用JavaScript的Date对象的getDay
方法。
如:获取当天是星期几,则为:
new Date().getDay();
//返回0-6,0对应星期天,1-6对应星期一到星期六
2、如果想给定某个时间是星期几,则应该把字符串转化为Date。
new Date('2015-09-27').getDay();//将返回0,表示星期天
3、我们把得到的星期几的数字转换成文字
export const weekDay = function(time: string) {
const weekNum = new Date(time).getDay();
let week = "";
switch (weekNum) {
case 0:
week = "星期天";
break;
case 1:
week = "星期一";
break;
case 2:
week = "星期二";
break;
case 3:
week = "星期三";
break;
case 4:
week = "星期四";
break;
case 5:
week = "星期五";
break;
case 6:
week = "星期六";
break;
}
return week;
};
更优雅的写法:对象属性判断法
export const weekDay = function(time: string) {
const weekNum = new Date(time).getDay();
const week= {
0: '星期天',
1: '星期一',
2: '星期二',
3: '星期三',
4: '星期四',
5: '星期五',
6: '星期六'
}
return week[weekNum ] ? week[weekNum ] : '日期错误';
}
方法二:使用数组
感觉是相对比较简洁的写法了
export const weekDay = function(time: string) {
let datelist = ['周日','周一','周二','周三','周四','周五','周六',]
return datelist[new Date(time).getDay()];
}