setup() {
    //现在的时间
    let dataTime = ref("");
    //今天星期
    const day = ref("");
    let timer;

    //获取当前的时间
    const getNowTime = () => {
      //时间戳
      const Dates = new Date();
      //年份
      const Year = Dates.getFullYear();
      //星期
      const data: number = Dates.getDay();
      //月份下标是0-11
      const Months = Dates.getMonth() + 1 < 10? "0" + (Dates.getMonth() + 1): Dates.getMonth() + 1;
      //具体的天数
      const Day = Dates.getDate() < 10 ? "0" + Dates.getDate() : Dates.getDate();
      //小时
      const Hours =Dates.getHours() < 10 ? "0" + Dates.getHours() : Dates.getHours();
      //分钟
      const Minutes =Dates.getMinutes() < 10 ? "0" + Dates.getMinutes(): Dates.getMinutes();
      //秒
      const Seconds =Dates.getSeconds() < 10 ? "0" + Dates.getSeconds(): Dates.getSeconds();
      dataTime.value = `${Hours}:${Minutes}:${Seconds} ${Year}.${Months}.${Day}`;
      day.value = `${data}`;

      //数字转化为汉字(switch写法)
      //switch (day.value as any) {
      //  case "1":
      //    day.value = "一";
      //    break;
      //  case "2":
      //    day.value = "二";
      //    break;
      //  case "3":
      //    day.value = "三";
      //    break;
      //  case "4":
      //    day.value = "四";
      //    break;
      //  case "5":
      //    day.value = "五";
      //    break;
      //  case "6":
      //    day.value = "六";
      //    break;
      //  case "7":
      //    day.value = "天";
      //    break;
      //}

      //数字转化为汉字(优化写法)
      let arr=["星期1","星期2","星期3","星期4","星期5","星期6","星期7"]
      let arr1=["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]
      for(let i in arr){
        if(arr[i]==day.value){
          day.value=arr1[i]
        }
      }
      return dataTime.value;
    }

   //挂载定时器
    onMounted(() => {
      timer = setInterval(() => {
        getNowTime();
      }, 1000);
    });

    onBeforeMount(() => {
      // 清理定时器要处理 timer 的类型
      clearInterval(Number(timer));
    });

    return{
      dataTime,
      day
    }
}
<template>
    <div class="time">
      <div>星期{{ day }}</div>
      <div>{{ dataTime }}</div>
    </div>
</template>

原文引用@Fx_cap的博客,并且运用switch-case进行时间的汉字转换

Logo

前往低代码交流专区

更多推荐