updateTime
函数详解
const currentTime = ref('')
const currentDate = ref('')
let timer: ReturnType<typeof setInterval>
onMounted(() => {
updateTime()
timer = setInterval(updateTime, 60000) // 每分钟更新一次
})
onBeforeUnmount(() => {
clearInterval(timer)
})
// 更新时间的函数
const updateTime = () => {
const now = new Date()
const hours = String(now.getHours()).padStart(2, '0')
const minutes = String(now.getMinutes()).padStart(2, '0')
currentTime.value = `${hours}:${minutes}`
const year = now.getFullYear()
const month = now.getMonth() + 1
const day = now.getDate()
const weekday = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'][now.getDay()]
currentDate.value = `${year}-${month}-${day} ${weekday}`
}
const updateTime = () => {
const now = new Date()
创建当前时间对象
const hours = String(now.getHours()).padStart(2, '0')
const minutes = String(now.getMinutes()).padStart(2, '0')
获取小时与分钟,
padStart(2, '0')
确保个位数前补零(如08:05
而不是8:5
)
const year = now.getFullYear()
const month = now.getMonth() + 1
const day = now.getDate()
获取当前年份、月份(注意
getMonth()
从 0 开始,所以要 +1)、日期。
const weekday = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'][now.getDay()]
获取当前星期几,
getDay()
返回 06,对应星期日星期六。