directive.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * 时间格式化工具函数
  3. * @param value 时间戳或日期字符串
  4. * @param format 格式化字符串,默认:YYYY-MM-DD HH:mm:ss
  5. * @returns 格式化后的时间字符串
  6. */
  7. export function changtime(value: number | string | Date, format: string = 'YYYY年MM月'): string {
  8. if (!value)
  9. return ''
  10. const date = new Date(value)
  11. // 检查日期是否有效
  12. if (Number.isNaN(date.getTime()))
  13. return ''
  14. const year = date.getFullYear()
  15. const month = String(date.getMonth() + 1).padStart(2, '0')
  16. const day = String(date.getDate()).padStart(2, '0')
  17. const hours = String(date.getHours()).padStart(2, '0')
  18. const minutes = String(date.getMinutes()).padStart(2, '0')
  19. const seconds = String(date.getSeconds()).padStart(2, '0')
  20. return format
  21. .replace('YYYY', String(year))
  22. .replace('MM', month)
  23. .replace('DD', day)
  24. .replace('HH', hours)
  25. .replace('mm', minutes)
  26. .replace('ss', seconds)
  27. }
  28. /**
  29. * 注册全局过滤器(Vue 3 兼容方式)
  30. * 在 main.ts 中调用此函数注册全局过滤器
  31. */
  32. export function registerGlobalFilters(app: any): void {
  33. // 注册全局属性,用于在模板中通过 $filters.changtime 使用
  34. app.config.globalProperties.$filters = {
  35. changtime
  36. }
  37. // 注册全局方法,使过滤器语法 | changtime 可以工作
  38. app.mixin({
  39. methods: {
  40. changtime
  41. }
  42. })
  43. }