javascript实现时间走动

get_time = function get_time() {
    var date = new Date();  //获取时间对象
    var year = date.getFullYear(); //获取年
    var month = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);//获取月份。获取的月份比真实的月份少一个月。所以这里得+1
    var day = (date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate()); //获取日
    var week = date.getDay();//返回0--6。当中0表示星期天,1--6代表星期一到星期六
    var weekStr = "未知";
    var hours = (date.getHours() < 10 ? "0" + (date.getHours()) : date.getHours()); //获取时(24小时制)
    var minutes = (date.getMinutes() < 10 ? "0" + (date.getMinutes()) : date.getMinutes());  //获取分
    var seconds = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());  //获取秒
    //处理星期的显示           
    switch (week) {
        case 1:
            weekStr = "一 "
            break;
        case 2:
            weekStr = "二 "
            break;
        case 3:
            weekStr = "三 "
            break;
        case 4:
            weekStr = "四 "
            break;
        case 5:
            weekStr = "五 "
            break;
        case 6:
            weekStr = "六 "
            break;
        default:
            weekStr = "日 ";
    }
    document.getElementById("timeMsg").innerHTML =
        `
${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}星期${weekStr}
` /* 或"
"+ "" + hours + ":" + minutes + ":" + seconds + ""+ "" + year + "年" + month + "月" + day + "日" + "星期" + weekStr + "" + "
"; */ } //setInterval动作的作用是每隔一定时间就调用函数,方法或对象 setInterval("get_time()", 1000);//设置每隔1豪秒调用一下上面的方法

你可能感兴趣的:(javascript实现时间走动)