dateUtil.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { reactive, toRefs } from "vue";
  2. import { tryOnMounted, tryOnUnmounted } from "@vueuse/core";
  3. import dayjs from "dayjs";
  4. const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
  5. const DATE_FORMAT = "YYYY-MM-DD";
  6. export function formatToDateTime(date?: dayjs.ConfigType, format = DATE_TIME_FORMAT): string {
  7. return dayjs(date).format(format);
  8. }
  9. export function formatToDate(date?: dayjs.ConfigType, format = DATE_FORMAT): string {
  10. return dayjs(date).format(format);
  11. }
  12. export function formatToTime(time?: dayjs.ConfigType, format = "HH:mm:ss"): string {
  13. return dayjs(time).format(format);
  14. }
  15. export const useNow = (immediate = true) => {
  16. let timer: ReturnType<typeof setInterval>;
  17. const state = reactive({
  18. year: 0,
  19. month: 0,
  20. week: "",
  21. day: 0,
  22. hour: "",
  23. minute: "",
  24. second: 0,
  25. meridiem: "",
  26. });
  27. const update = () => {
  28. const now = dayjs();
  29. const h = now.format("HH");
  30. const m = now.format("mm");
  31. const s = now.get("s");
  32. state.year = now.get("y");
  33. state.month = now.get("M") + 1;
  34. state.week = "星期" + ["日", "一", "二", "三", "四", "五", "六"][now.day()];
  35. state.day = now.get("date");
  36. state.hour = h;
  37. state.minute = m;
  38. state.second = s;
  39. state.meridiem = now.format("A");
  40. };
  41. function start() {
  42. update();
  43. clearInterval(timer);
  44. timer = setInterval(() => update(), 1000);
  45. }
  46. function stop() {
  47. clearInterval(timer);
  48. }
  49. tryOnMounted(() => {
  50. if (immediate) {
  51. start();
  52. }
  53. });
  54. tryOnUnmounted(() => {
  55. stop();
  56. });
  57. return {
  58. ...toRefs(state),
  59. start,
  60. stop,
  61. };
  62. };