vuez中获取当前时间的js方法

这是一个使用Vue.js编写的组件,它实时显示当前的年月日时分秒。组件在创建时调用`nowTimes`方法获取并格式化时间,并通过设置定时器每秒更新时间。时间格式化函数`timeFormate`将时间戳转换为易读的日期和时间格式。虽然有清除定时器的尝试,但实际代码中清除操作可能不正确,可能会导致定时器无法停止。
摘要由CSDN通过智能技术生成

<template>

    <div> {{ nowTime }} </div>

</template>

<script>

export default {

    data() {

        return {

                nowTime: '',//显示当前时间

        }

    },

    created() {

        this.nowTimes() //获取时间的方法

    },

    methods: {

        //显示当前时间(年月日时分秒)

        timeFormate(timeStamp) {

            let year = new Date(timeStamp).getFullYear();

            let month = new Date(timeStamp).getMonth() + 1 < 10 ? "0" + (new Date(timeStamp).getMonth() + 1) : new Date(timeStamp).getMonth() + 1;

            let date = new Date(timeStamp).getDate() < 10 ? "0" + new Date(timeStamp).getDate() : new Date(timeStamp).getDate();

            let hh = new Date(timeStamp).getHours() < 10 ? "0" + new Date(timeStamp).getHours() : new Date(timeStamp).getHours();

            let mm = new Date(timeStamp).getMinutes() < 10 ? "0" + new Date(timeStamp).getMinutes() : new Date(timeStamp).getMinutes();

            let ss = new Date(timeStamp).getSeconds() < 10 ? "0" + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds();

            this.nowTime = year + "年" + month + "月" + date + "日" + " " + hh + ":" + mm + ':' + ss;

        },

        nowTimes() {

            this.timeFormate(new Date());

            setInterval(this.nowTimes, 1000);

            //清除定时器,解决网页卡顿问题

            clearInterval(this.nowTimes);

            this.nowTimes = null;

        },

    },

    // beforeDestroy() { //销毁定时器

    //     clearInterval(this.nowTimes)

    //     this.nowTimes = null;

    // }

}

</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值