JS 获取星期几的四种写法

//第一种方法
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); 
//第二种方法
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("下午")
}

获取未来七天

var xData = function () { //获取当前时间的未来7天
    var dd = new Date();
    var arrDate = [];
    var arrWeek = new Array("日", "一", "二", "三", "四", "五", "六");
    for(var i = 0; i < 7; i++){
        //dd.setDate(dd.getDate()+1);  //此处为包括今天的未来七天
        arrDate.push(dd.getFullYear() + '年' + (dd.getMonth()+1) + "月" + dd.getDate() + '日' + '星期' + arrWeek[dd.getDay()]);
        dd.setDate(dd.getDate()+1);  //此处为不包括今天的未来七天
    }
    console.log(arrDate)
    return arrDate;
}();

你可能感兴趣的:(JS 获取星期几的四种写法)