useTime.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { ref, onMounted, onUnmounted } from 'vue';
  2. /**
  3. * @description 获取本地时间
  4. */
  5. export function useTime() {
  6. let timer; // 定时器
  7. const year = ref(0); // 年份
  8. const month = ref(0); // 月份
  9. const week = ref(''); // 星期几
  10. const day = ref(0); // 天数
  11. const hour = ref<number | string>(0); // 小时
  12. const minute = ref<number | string>(0); // 分钟
  13. const second = ref(0); // 秒
  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 = date.getSeconds();
  28. };
  29. // 原生时间格式化
  30. // new Intl.DateTimeFormat('zh', {
  31. // year: 'numeric',
  32. // month: '2-digit',
  33. // day: '2-digit',
  34. // hour: '2-digit',
  35. // minute: '2-digit',
  36. // second: '2-digit',
  37. // hour12: false
  38. // }).format(new Date())
  39. updateTime();
  40. onMounted(() => {
  41. clearInterval(timer);
  42. timer = setInterval(() => updateTime(), 1000);
  43. });
  44. onUnmounted(() => {
  45. clearInterval(timer);
  46. });
  47. return { month, day, hour, minute, second, week };
  48. }