根据自己需要进行选择使用,有静态时间和动态时间
new Date():获取当前时间
getFullYear():获取年份
getMonth():获取月份
getDay():获取天
getHours():获取小时
getMinutes():获取分钟
getSeconds():获取秒数
第一种方法
<template>
<div class="box">
<h1>测试</h1>
<h1>{{ format }}</h1>
</div>
</template>
<script setup>
// 01
const format=computed(()=>{
const oDate=new Date()
const year=oDate.getFullYear()
const month=oDate.getMonth()+1
const day=oDate.getDay().toString()
const hour=oDate.getHours()
const minutes=oDate.getMinutes()
const seconds=oDate.getSeconds()
return year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds
})
</script>
<style lang="less" scoped></style>
第二种方法
<template>
<div class="box">
<h1>测试</h1>
<h1>{{ formatdata }}</h1>
</div>
</template>
<script setup>
import {ref,computed,watchEffect} from 'vue'
// 02
const formatdata=computed(()=>{
const oDate=new Date()
const year=oDate.getFullYear()
const month=oDate.getMonth()+1
const day=oDate.getDay().toString()
const hour=oDate.getHours()
return year+'-'+month+'-'+day
})
</script>
<style lang="less" scoped></style>
第三种方法
<template>
<div class="box">
<h1>测试</h1>
<h1>{{ currenttime }}</h1>
</div>
</template>
<script setup>
import {ref,computed,watchEffect} from 'vue'
// 03
const currenttime=ref('')
const setdate=(oDate)=>{
const year = oDate.getFullYear()
const month = (oDate.getMonth() + 1).toString().padStart(2, '0')
const day = oDate.getDate().toString().padStart(2, '0')
const hour = oDate.getHours().toString().padStart(2, '0')
const minutes = oDate.getMinutes().toString().padStart(2, '0')
const seconds = oDate.getSeconds().toString().padStart(2, '0')
return year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds
}
watchEffect(()=>{
setInterval(() => {
currenttime.value=setdate(new Date())
}, 1000);
})
</script>
<style lang="less" scoped></style>
第四种方法
<template>
<div class="box">
<h1>测试</h1>
<h2>{{ currentDateTime }}</h2>
</div>
</template>
<script setup>
import {ref,computed,watchEffect} from 'vue'
// 第三方插件
import dayjs from 'dayjs'
// 04
const currentDateTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
watchEffect(()=>{
setInterval(() => {
// dayjs
currentDateTime.value=dayjs().format('YYYY-MM-DD HH:mm:ss')
}, 1000);
})
</script>
<style lang="less" scoped></style>
第五种方法
<template>
<div class="box">
<h1>测试</h1>
// 根据拼接符号,这里是/
<h2>{{ formattime(time,'/') }}</h2>
</div>
</template>
<script setup>
import {ref,computed,watchEffect} from 'vue'
// 05
const time=ref(Date.now())
// 默认为-
const formattime=(timer,flg='-')=>{
const oDate=new Date(timer)
const year=oDate.getFullYear()
const month=(oDate.getMonth()+1).toString().padStart(2,'0')
const day=oDate.getDay().toString().padStart(2,'0')
return year+flg+month+flg+day
}
</script>
<style lang="less" scoped></style>