js动态获取当前时间并显示星期数

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 300px;
            height: 150px;
            background-color: #2e3344;
            color: white;
            margin: 300px auto;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        h2 {
            text-align: center;
            font-size: 60px;


        }

        p {
            text-align: center;
        }
        span{
            font-size: 20px;
            margin-right: 15px;
        }
    </style>
</head>

<body>
    <div class="box">
        <!-- 时分 -->
        <h2></h2>
        <p>
            <!-- 存储月日 -->
            <span class="one"></span>
            <!-- 存储星期 -->
            <span class="two"></span>
       
        </p>

    </div>



    <div></div>
    <script>
//获取对应的元素
        const div = document.querySelector('div')
        const h2 = document.querySelector('h2')
        const one = document.querySelector('.one')
        const two = document.querySelector('.two')
        const three = document.querySelector('.three')

//封装倒计时函数,根据需求返结果
        function getTime() {
            let date = new Date()//当前时间
            let year = date.getFullYear()//当前年份
            let month = date.getMonth() + 1//当前月
            let day = date.getDate()//天数
            let week = date.getDay()//星期数
            let hour = date.getHours()//时
            hour = hour < 10 ? '0' + hour : hour
            let minute = date.getMinutes()//分
            minute = minute < 10 ? '0' + minute : minute
            let second = date.getSeconds()//秒
            second = second < 10 ? '0' + second : second

            return ` ${hour}:${minute} `
        }
        h2.innerHTML = getTime()//获取当前时间的时,分
        //将星期数用数组包裹
        const arr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
        setInterval(function () {
            h2.innerHTML = getTime()
        }, 1000)
        let date = new Date()
        one.innerHTML = `${date.getMonth() + 1}月${date.getDate()}日`//获取当前时间的月日
        two.innerHTML = `${arr[date.getDay()]}`//获取星期数

    </script>
</body>

</html>
相关推荐
美酒没故事°6 分钟前
npm源管理器:nrm
前端·npm·npm源
用户22152044278007 分钟前
vue3组件间的通讯方式
前端·vue.js
三十_A25 分钟前
【实录】使用 patch-package 修复第三方 npm 包中的 Bug
前端·npm·bug
下位子33 分钟前
『AI 编程』用 Claude Code 从零到一开发全栈减脂追踪应用
前端·ai编程·claude
tyro曹仓舒33 分钟前
Vue单文件组件到底需不需要写name
前端·vue.js
用户479492835691533 分钟前
面试官:讲讲2FA 双因素认证原理
前端·后端·安全
乐影34 分钟前
TS 模板字符串类型:从基础到进阶的类型编程魔法
前端·typescript
龙在天35 分钟前
CSS 属性值的计算与过程
前端
云鹤_36 分钟前
【Amis源码阅读】组件注册方法远比预想的多!
前端·低代码
xinfei38 分钟前
ES6 新特性 从 ECMAScript 2015(ES6)到 ECMAScript 2025
前端