JavaScript动态显示当前时间

 前端写项目时, 有时会需要获取当前时间, 虽然使用度不高, 难免有需要的时候.

下面整理获取当前时间代码思路

使用 new Date() 获取 当前时间的时间戳

  • getFullYear(): 时间戳转换的年份
  • getMonth() + 1: 月份
  • getDate(): 日期
  • getHours()
  • getMinutes()
  • getSeconds() 

根据需要获取相应的时间类型

var showTime = document.querySelector('.showTime');
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
// const year = date.getFullYear();
// const month = date.getMonth() + 1;
// const day = date.getDate();
// showTime.innerHTML = (`${year} : ${month} : ${day}`);
// showTime.innerHTML = (`${date.toLocaleString()}`);   //"1995/12/17 上午3:24:00"
showTime.innerHTML = `${date.toDateString()}--${hour} : ${minutes} : ${seconds}`  // "Sun Dec 17 1995"

其中含有方法快速获取固定类型的年月日时间类型

  • toLocaleString(): "1995/12/17 上午3:24:00"
  • toDateString(): "Sun Dec 17 1995"

获取DOM元素, 在元素中使用拼接, 通过innerHTML/innerText 写入元素, 显示在页面上

动态显示时间

使用setTimeout()定时器, 否则只是显示渲染页面的当前时间

var t = null;
//添加定时器, 开始运行
t = setTimeout(time, 1000);
function time() {

    //清除定时器
    clearTimeout(t);

    //获取时间, 定义要显示的类型
    ...

    //设定定时器, 循环运行
    t = setTimeout(time, 1000);
} 

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>当前时间</title>
    <style>
        *{margin: 0;padding: 0;background-color: #000;}
        .container{
            width: 100vw;
            height: calc(100vh);
        }
        .showTime{
            color: aqua;
            font-size: 100px;
            width: 100%;
            margin: auto;
            text-align: center;
            line-height: calc(100vh);

        }
    </style>
</head>
<body>
    <div class="container">
        <div class="showTime"></div>
    </div>

    <script>
        var t = null;
        t = setTimeout(time, 1000);
        function time() {
            clearTimeout(t);
            var showTime = document.querySelector('.showTime');
            const date = new Date();
            const hour = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
             showTime.innerHTML = `${date.toDateString()}--${hour} : ${minutes} : ${seconds}`
            t = setTimeout(time, 1000);
        }          
    </script>


</body>
</html>

实现页面显示也可以通过document.write()直接写入在标签内部

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值