Vue+JS get the current real time

Principle: Call the time function to obtain the year, month, day, etc. and encapsulate it into the getDate function written by yourself to obtain the current time. The getDate function will re-copy the obtained function to the variable nowDate defined in data , and then set the timer to call for one second. Once getDate function, then put the timer into the life cycle function created , and finally use the interpolation syntax to put the nowDate in the specified position

The implementation code is as follows:

<template>
    <div class="container">
        <div class="header">            
            <div class="dateTime">当前时间:  {
   
   { nowDate }}</div>
        </div>
        <div class="footer"></div>
    </div>
</template>
 
<script>
export default {
    name: "realTime",
    created() {
        this.currentTime()
    },
    data() {
        return {
            nowDate:'',
        }
    },
    methods: {
        
         //获取当前时间
         
        getDate() {
            let date = new Date();
            let year = date.getFullYear(); // 年
            let month = date.getMonth() + 1; // 月
            let day = date.getDate(); // 日
            let week = date.getDay(); // 星期
            let weekArr = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ];
            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; // 如果只有一位,则前面补零
            this.nowDate = `${year}年${month}月${day}日 ${hour}时${minute}分${second}秒 ${weekArr[week]}`;
        },
       
        //定时器调取当前时间
        
        currentTime(){
            setInterval(()=>{
                this.getDate()
            },1000)
        },
 
    }
}
</script>

Guess you like

Origin blog.csdn.net/qq_42691298/article/details/129245931