useTime.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { ref } from "vue";
  2. /**
  3. * @description 获取本地时间
  4. */
  5. export const useTime = () => {
  6. const year = ref(0); // 年份
  7. const month = ref(0); // 月份
  8. const week = ref(""); // 星期几
  9. const day = ref(0); // 天数
  10. const hour = ref<number | string>(0); // 小时
  11. const minute = ref<number | string>(0); // 分钟
  12. const second = ref<number | string>(0); // 秒
  13. const nowTime = ref<string>(""); // 当前时间
  14. // 更新时间
  15. const updateTime = () => {
  16. const date = new Date();
  17. year.value = date.getFullYear();
  18. month.value = date.getMonth() + 1;
  19. week.value = "日一二三四五六".charAt(date.getDay());
  20. day.value = date.getDate();
  21. hour.value =
  22. (date.getHours() + "")?.padStart(2, "0") ||
  23. new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getHours());
  24. minute.value =
  25. (date.getMinutes() + "")?.padStart(2, "0") ||
  26. new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getMinutes());
  27. second.value =
  28. (date.getSeconds() + "")?.padStart(2, "0") ||
  29. new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getSeconds());
  30. nowTime.value = `${year.value}年${month.value}月${day.value} ${hour.value}:${minute.value}:${second.value}`;
  31. };
  32. updateTime();
  33. return { year, month, day, hour, minute, second, week, nowTime };
  34. };