useTime.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { ref, onMounted, onUnmounted } from 'vue';
  2. /**
  3. * @description 获取本地时间
  4. */
  5. export function useTime() {
  6. let timer: any; // 定时器
  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(
  24. date.getHours()
  25. );
  26. minute.value =
  27. (date.getMinutes() + '')?.padStart(2, '0') ||
  28. new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(
  29. date.getMinutes()
  30. );
  31. second.value = date.getSeconds();
  32. };
  33. // 原生时间格式化
  34. // new Intl.DateTimeFormat('zh', {
  35. // year: 'numeric',
  36. // month: '2-digit',
  37. // day: '2-digit',
  38. // hour: '2-digit',
  39. // minute: '2-digit',
  40. // second: '2-digit',
  41. // hour12: false
  42. // }).format(new Date())
  43. updateTime();
  44. onMounted(() => {
  45. clearInterval(timer);
  46. timer = setInterval(() => updateTime(), 1000);
  47. });
  48. onUnmounted(() => {
  49. clearInterval(timer);
  50. });
  51. return { month, day, hour, minute, second, week };
  52. }