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>
相关推荐
Profile排查笔记1 小时前
指纹浏览器环境异常排查:Fingerprint、Profile、Proxy、Session 和 Task Log 怎么看
前端·人工智能·后端·自动化
京韵养生记1 小时前
【无标题】
java·服务器·前端
大气的小蜜蜂2 小时前
领域层的服务
java·前端·数据库
星栈2 小时前
LiveView 的 LiveComponent:比 React 组件更轻,但我一开始真的把它用错了
前端·前端框架·elixir
竹林8182 小时前
用 Pinata + IPFS 存 NFT 元数据踩了三天坑,我总结了这份完整的前端实现方案
javascript
林希_Rachel_傻希希2 小时前
web性能优化之延迟加载图片和<inframe>
前端·javascript·面试
maxmaxma2 小时前
Konva 从入门到实践 - day1
前端
火星校尉2 小时前
一场数据基建与消费场景的跨界实验
java·前端·数据库·python·php
W是笔名3 小时前
python_let`s try it 6___BMI计算器
java·前端·python
risc1234563 小时前
Lucene80DocValuesConsumer 五种类型源码阅读顺序
java·服务器·前端