util.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // util.js - 工具函数
  2. /**
  3. * 格式化日期
  4. */
  5. const formatDate = (date, format = 'YYYY-MM-DD HH:mm') => {
  6. const d = new Date(date);
  7. const year = d.getFullYear();
  8. const month = String(d.getMonth() + 1).padStart(2, '0');
  9. const day = String(d.getDate()).padStart(2, '0');
  10. const hour = String(d.getHours()).padStart(2, '0');
  11. const minute = String(d.getMinutes()).padStart(2, '0');
  12. return format
  13. .replace('YYYY', year)
  14. .replace('MM', month)
  15. .replace('DD', day)
  16. .replace('HH', hour)
  17. .replace('mm', minute);
  18. };
  19. /**
  20. * 格式化时间显示(如:3小时前、刚刚)
  21. */
  22. const formatTimeAgo = (date) => {
  23. const now = new Date();
  24. const d = new Date(date);
  25. const diff = Math.floor((now - d) / 1000);
  26. if (diff < 60) return '刚刚';
  27. if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
  28. if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
  29. if (diff < 604800) return Math.floor(diff / 86400) + '天前';
  30. return formatDate(date, 'MM-DD');
  31. };
  32. /**
  33. * 计算剩余时间
  34. */
  35. const calcRemainingTime = (deadline) => {
  36. const now = new Date();
  37. const end = new Date(deadline);
  38. const diff = end - now;
  39. if (diff <= 0) return { text: '已截止', isOverdue: true };
  40. const hours = Math.floor(diff / 3600000);
  41. const minutes = Math.floor((diff % 3600000) / 60000);
  42. const seconds = Math.floor((diff % 60000) / 1000);
  43. return {
  44. hours,
  45. minutes,
  46. seconds,
  47. text: `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`,
  48. isOverdue: false
  49. };
  50. };
  51. /**
  52. * 防抖函数
  53. */
  54. const debounce = (fn, delay = 500) => {
  55. let timer = null;
  56. return function (...args) {
  57. if (timer) clearTimeout(timer);
  58. timer = setTimeout(() => fn.apply(this, args), delay);
  59. };
  60. };
  61. module.exports = {
  62. formatDate,
  63. formatTimeAgo,
  64. calcRemainingTime,
  65. debounce
  66. };