| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- // util.js - 工具函数
- /**
- * 格式化日期
- */
- const formatDate = (date, format = 'YYYY-MM-DD HH:mm') => {
- const d = new Date(date);
- const year = d.getFullYear();
- const month = String(d.getMonth() + 1).padStart(2, '0');
- const day = String(d.getDate()).padStart(2, '0');
- const hour = String(d.getHours()).padStart(2, '0');
- const minute = String(d.getMinutes()).padStart(2, '0');
-
- return format
- .replace('YYYY', year)
- .replace('MM', month)
- .replace('DD', day)
- .replace('HH', hour)
- .replace('mm', minute);
- };
- /**
- * 格式化时间显示(如:3小时前、刚刚)
- */
- const formatTimeAgo = (date) => {
- const now = new Date();
- const d = new Date(date);
- const diff = Math.floor((now - d) / 1000);
-
- if (diff < 60) return '刚刚';
- if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
- if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
- if (diff < 604800) return Math.floor(diff / 86400) + '天前';
- return formatDate(date, 'MM-DD');
- };
- /**
- * 计算剩余时间
- */
- const calcRemainingTime = (deadline) => {
- const now = new Date();
- const end = new Date(deadline);
- const diff = end - now;
-
- if (diff <= 0) return { text: '已截止', isOverdue: true };
-
- const hours = Math.floor(diff / 3600000);
- const minutes = Math.floor((diff % 3600000) / 60000);
- const seconds = Math.floor((diff % 60000) / 1000);
-
- return {
- hours,
- minutes,
- seconds,
- text: `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`,
- isOverdue: false
- };
- };
- /**
- * 防抖函数
- */
- const debounce = (fn, delay = 500) => {
- let timer = null;
- return function (...args) {
- if (timer) clearTimeout(timer);
- timer = setTimeout(() => fn.apply(this, args), delay);
- };
- };
- module.exports = {
- formatDate,
- formatTimeAgo,
- calcRemainingTime,
- debounce
- };
|