js中如何获取星期几的写法
第一种:利用if...else...
var str = "";
var week = new Date().getDay();
if (week == 0) {
str = "今天是星期日";
} else if (week == 1) {
str = "今天是星期一";
} else if (week == 2) {
str = "今天是星期二";
} else if (week == 3) {
str = "今天是星期三";
} else if (week == 4) {
str = "今天是星期四";
} else if (week == 5) {
str = "今天是星期五";
} else if (week == 6) {
str = "今天是星期六";
}
alert(str);
第二种:利用switch循环
var str = "";
var week = new Date().getDay();
switch (week) {
case 0 :
str += "今天是星期日";
break;
case 1 :
str += "今天是星期一";
break;
case 2 :
str += "今天是星期二";
break;
case 3 :
str += "今天是星期三";
break;
case 4 :
str += "今天是星期四";
break;
case 5 :
str += "今天是星期五";
break;
case 6 :
str += "今天是星期六";
break;
}
alert(str);
第三种:利用数组
var a = new Array("日", "一", "二", "三", "四", "五", "六");
var week = new Date().getDay();
var str = "今天是星期"+ a[week];
alert(str);
第四种:利用获取字符的方法
var str = "今天是星期" + "日一二三四五六".charAt(new Date().getDay());
alert(str);
//判断时间是凌晨,早上,上午,中午,下午,傍晚,晚上,深夜
var now = new Date();
var hour = now.getHours() ;
if(hour < 6){
document.write("凌晨")
} else if (hour < 9){00000
document.write("早上")
} else if (hour < 12){
document.write("上午")
} else if (hour < 14){
document.write("中午")
} else if (hour < 17){
document.write("下午")
} else if (hour < 19){
document.write("傍晚")
} else if (hour < 22){
document.write("晚上")
} else {
document.write("深夜")
}
//判断时间是上午,下午
if(hour <= 12){
document.write("上午")
}else{
document.write("下午")
}