JS 获取星期几的四种写法

第一种写法 

var str = "今天是星期" + "日一二三四五六".charAt(new Date().getDay());
document.getElementById("day").innerHTML=str;

第二张写法

var a = new Array("日", "一", "二", "三", "四", "五", "六");  
var week = new Date().getDay();  
var str = "今天是星期"+ a[week];  
document.getElementById("day").innerHTML=str;

第三种写法

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 = "今天是星期六";  
}  
document.getElementById("day").innerHTML=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;  
}  
document.getElementById("day").innerHTML=str; 

 

获取年月日时分秒星期并实时更新

//js获取日期
function NowTime() {
    var now= new Date();
    var hours=now.getHours();
    var minutes=now.getMinutes();
    var year=now.getFullYear();
    var month=now.getMonth();
    var date=now.getDate();
//获取相应ID
    document.getElementById("minutes").innerHTML=hours+":"+minutes;
    document.getElementById("time_data").innerHTML=year+"年"+(month+1)+"月"+date+"日";
    var str = "星期" + "日一二三四五六".charAt(new Date().getDay())
    document.getElementById("day").innerHTML=str;
}
//页面加载调用
window.οnlοad=function(){
    //每1秒刷新时间
    setInterval("NowTime()",1000);
}

JS 获取星期几的四种写法_第1张图片

你可能感兴趣的:(js)