美文网首页
日期函数及时钟案例

日期函数及时钟案例

作者: 追马的时间种草 | 来源:发表于2019-09-26 15:31 被阅读0次

日期对象的基本操作

let time=new Date();
/*
    获取当前客户单本地时间
        这个时间是可以修改的,所以不能作为重要的从参考依据
        Fri Aug 30 2019 13:10:54 GMT+0800 (中国标准时间)
        获取的结果不是字符串类型的,属于日期对象(或者说是Data这个类的实例对象)
*/
typeof time; //"object"

标准日期对象中提供了一些属性和方法,供我们操作日期信息

  • getFullYear() 年

  • getMonth()月 返回0-11 一月到12月

  • getDate()日

  • getDay()星期 返回 0-6 周日到周六

  • getHours()

  • getMinute()分

  • getSecond()秒

  • getMilisecond()毫秒

  • getTime()获取当前日期距离1970/1/1 00:00:00的毫秒差

  • toLocalDateString 获取年月日(字符串) 如: "2019/8/30"

  • tolocaleString() 获取完整的日期字符创 如: "2019/8/30 下午1:19:04"

时钟案例:

<body>
    <style>
        *{
            margin:0;
            padding: 0;
        }
        #clockBox{
            position: absolute;
            right: 0;
            top: 0;
            padding:0 15px;
            line-height: 70px;
            font-size: 25px;
            color:rgb(223, 16, 51);
            background: -webkit-linear-gradient(top left, lightblue, lightcoral, lightcyan) ;
           
        }
    </style>
    <div id="clockBox">
        时间:2019年07月 星期五 上午 10:25:03
    </div>
</body>
<script>
    let clockBox=document.getElementById('clockBox');

    function addZero(val){
        val=Number(val);
        return val<10?"0"+val:val
    }

    function queryDate(){
        let time=new Date();
        let year=time.getFullYear(),
            month=time.getMonth()+1,
            day=time.getDate(),
            week=time.getDay(),
            hours=time.getHours(),
            minu=time.getMinutes(),
            seconds=time.getSeconds();
        let weekAry=['7','1',"2",'3',"4","5","6"]
        let result=year+"年"+addZero(month)+"月"+addZero(day)+"日";
            result+="星期"+weekAry[week]+" ";
            result+=addZero(hours)+":"+addZero(minu)+":"+addZero(seconds);
        clockBox.innerHTML=result;
    }
    queryDate();
    setInterval(queryDate,1000)
</script>

效果图

动态时钟图

相关文章

网友评论

      本文标题:日期函数及时钟案例

      本文链接:https://www.haomeiwen.com/subject/mgznectx.html