index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * 通用工具类
  3. * 此代码由AI生成
  4. */
  5. /**
  6. * 格式化时间
  7. * @param {string|Date} time
  8. * @param {string} pattern
  9. */
  10. export function formatTime(time, pattern = 'yyyy-MM-dd HH:mm:ss') {
  11. if (!time) return ''
  12. const date = new Date(time)
  13. const o = {
  14. 'M+': date.getMonth() + 1,
  15. 'd+': date.getDate(),
  16. 'H+': date.getHours(),
  17. 'm+': date.getMinutes(),
  18. 's+': date.getSeconds()
  19. }
  20. if (/(y+)/.test(pattern)) {
  21. pattern = pattern.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  22. }
  23. for (const k in o) {
  24. if (new RegExp('(' + k + ')').test(pattern)) {
  25. pattern = pattern.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  26. }
  27. }
  28. return pattern
  29. }
  30. /**
  31. * 日期格式化展示(5分钟前,今天 HH:mm 等)
  32. */
  33. export function displayTime(time) {
  34. if (!time) return ''
  35. const date = new Date(time)
  36. const now = new Date()
  37. const diff = now.getTime() - date.getTime()
  38. if (diff < 60000) return '刚刚'
  39. if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  40. if (now.toDateString() === date.toDateString()) return '今天 ' + formatTime(date, 'HH:mm')
  41. const yesterday = new Date(now.getTime() - 86400000)
  42. if (yesterday.toDateString() === date.toDateString()) return '昨天 ' + formatTime(date, 'HH:mm')
  43. return formatTime(date, 'MM-dd HH:mm')
  44. }