vue3获取当前日期、时间和星期(格式:年月日 时分秒 星期)

<template>
    <div class="tri_box">
        <p>创建时间:{ { date }}</p>
    </div>
</template>
   
<script setup lang="ts">
import { ref, onMounted } from 'vue'

const date = ref('')
  //格式化时间的函数  。它接受一个数字类型的参数 time,表示需要格式化的时间。
  //如果 time 小于10,则返回一个带有前导零的字符串表示;
  //否则,将 time 转换为字符串后返回。
function formatTime(time: number) {
    return time < 10 ? `0${time}` : time
}
function updateTime() {
    const now = new Date()
    const year = now.getFullYear()  //年
    const month = now.getMonth() + 1 //月
    const day = now.getDate()    //日
    const hours = now.getHours()  //小时数
    const minutes = now.getMinutes()  //分钟数
    const seconds = now.getSeconds()  //秒数
    const week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][now.getDay()]  //星期
  //想展示什么  对应的展示即可 
  date.value = `${year}-${formatTime(month)}-${formatTime(day)} ${formatTime(hours)}:${formatTime(minutes)}:${formatTime(seconds)} ${week}`
}
  onMounted(() => {
    updateTime()
})
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44096999/article/details/131207411