cooldown.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * 冷却锁定与 UTC 时间解析工具函数
  3. */
  4. /**
  5. * 将可能缺失时区后缀的 UTC 日期字符串或 Date 对象标准化解析为 Date
  6. */
  7. export function parseUtcDate(dateStr?: string | Date | null): Date | null {
  8. if (!dateStr) return null;
  9. if (dateStr instanceof Date) {
  10. return isNaN(dateStr.getTime()) ? null : dateStr;
  11. }
  12. if (typeof dateStr !== 'string') return null;
  13. let normalized = dateStr.trim().replace(' ', 'T');
  14. if (!normalized) return null;
  15. // 若无时区标识 (Z 或 +08:00 / -05:00),补全 Z 作为 UTC 解析
  16. if (!normalized.endsWith('Z') && !normalized.includes('+') && !normalized.match(/-\d{2}:\d{2}$/)) {
  17. normalized += 'Z';
  18. }
  19. const d = new Date(normalized);
  20. return isNaN(d.getTime()) ? null : d;
  21. }
  22. /**
  23. * 判断当前资产是否处于冷却锁定中 (next_use_time > now)
  24. */
  25. export function isItemInCooldown(nextUseTime?: string | Date | null, nowMs: number = Date.now()): boolean {
  26. const targetDate = parseUtcDate(nextUseTime);
  27. if (!targetDate) return false;
  28. return targetDate.getTime() > nowMs;
  29. }
  30. /**
  31. * 计算剩余冷却时间格式化字符串 (例如: 1h20m, 14m32s, 45s),若已过期则返回 null
  32. */
  33. export function getCooldownRemainingTime(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
  34. const targetDate = parseUtcDate(nextUseTime);
  35. if (!targetDate) return null;
  36. const diffMs = targetDate.getTime() - nowMs;
  37. if (diffMs <= 0) return null;
  38. const diffSec = Math.floor(diffMs / 1000);
  39. const m = Math.floor(diffSec / 60);
  40. const s = diffSec % 60;
  41. const h = Math.floor(m / 60);
  42. const d = Math.floor(h / 24);
  43. if (d > 0) {
  44. return `${d}d${h % 24}h`;
  45. }
  46. if (h > 0) {
  47. return `${h}h${m % 60}m`;
  48. }
  49. if (m > 0) {
  50. return `${m}m${s}s`;
  51. }
  52. return `${s}s`;
  53. }
  54. /**
  55. * 详细中文剩余时间 (用于抽屉详情等场景)
  56. */
  57. export function getCooldownRemainingText(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
  58. const targetDate = parseUtcDate(nextUseTime);
  59. if (!targetDate) return null;
  60. const diffMs = targetDate.getTime() - nowMs;
  61. if (diffMs <= 0) return null;
  62. const diffSec = Math.floor(diffMs / 1000);
  63. const m = Math.floor(diffSec / 60);
  64. const s = diffSec % 60;
  65. const h = Math.floor(m / 60);
  66. const d = Math.floor(h / 24);
  67. if (d > 0) {
  68. return `${d}天${h % 24}小时`;
  69. }
  70. if (h > 0) {
  71. return `${h}小时${m % 60}分`;
  72. }
  73. if (m > 0) {
  74. return `${m}分${s}秒`;
  75. }
  76. return `${s}秒`;
  77. }