Vue 3 实现当前时间与日期显示(逐分钟刷新)代码详解

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,对应星期日星期六。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值