dateUtils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // utils/dateUtils.js
  2. /**
  3. * 智能时间格式化:返回 "今天 18:00"、"昨天 18:00" 等
  4. */
  5. export function formatSmartTime(timeStr) {
  6. if (!timeStr) return '未知';
  7. // iOS兼容格式
  8. const safeStr = timeStr.replace(' ', 'T');
  9. const inputDate = new Date(safeStr);
  10. if (isNaN(inputDate.getTime())) return '时间格式错误';
  11. const now = new Date();
  12. const inputDayStart = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate());
  13. const nowDayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  14. const diffTime = nowDayStart - inputDayStart;
  15. const oneDay = 1000 * 60 * 60 * 24;
  16. const timePart = inputDate.toTimeString().slice(0, 5); // HH:mm
  17. if (diffTime === 0) {
  18. return `今天 ${timePart}`;
  19. } else if (diffTime === oneDay) {
  20. return `昨天 ${timePart}`;
  21. } else if (diffTime === oneDay * 2) {
  22. return `前天 ${timePart}`;
  23. } else {
  24. return `${inputDate.getMonth() + 1}月${inputDate.getDate()}日 ${timePart}`;
  25. }
  26. }
  27. /**
  28. * 相对时间格式化:返回 "刚刚更新"、"5分钟前更新"、"3天前更新" 等
  29. */
  30. export function formatDate(dateStr) {
  31. if (!dateStr) return '未知';
  32. const parsedStr = dateStr.replace(' ', 'T');
  33. const date = new Date(parsedStr);
  34. if (isNaN(date.getTime())) return '无效时间';
  35. const now = new Date();
  36. const diff = Math.floor((now - date) / 1000 / 60); // 单位:分钟
  37. if (diff < 1) return '刚刚更新';
  38. if (diff < 5) return '1分钟前更新';
  39. if (diff < 10) return '5分钟前更新';
  40. if (diff < 60) return `${diff}分钟前更新`;
  41. if (diff < 120) return '1小时前更新';
  42. if (diff < 24 * 60) return `${Math.floor(diff / 60)}小时前更新`;
  43. if (diff < 7 * 24 * 60) return `${Math.floor(diff / (60 * 24))}天前更新`;
  44. return parsedStr.split('T')[0] + ' 更新';
  45. }
  46. export function getFormattedTime() {
  47. const now = new Date();
  48. const pad = n => n < 10 ? '0' + n : n;
  49. const year = now.getFullYear();
  50. const month = pad(now.getMonth() + 1);
  51. const day = pad(now.getDate());
  52. const hours = pad(now.getHours());
  53. const minutes = pad(now.getMinutes());
  54. const seconds = pad(now.getSeconds());
  55. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  56. }