| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- /**
- * 冷却锁定与 UTC 时间解析工具函数
- */
- /**
- * 将可能缺失时区后缀的 UTC 日期字符串或 Date 对象标准化解析为 Date
- */
- export function parseUtcDate(dateStr?: string | Date | null): Date | null {
- if (!dateStr) return null;
- if (dateStr instanceof Date) {
- return isNaN(dateStr.getTime()) ? null : dateStr;
- }
- if (typeof dateStr !== 'string') return null;
- let normalized = dateStr.trim().replace(' ', 'T');
- if (!normalized) return null;
- // 若无时区标识 (Z 或 +08:00 / -05:00),补全 Z 作为 UTC 解析
- if (!normalized.endsWith('Z') && !normalized.includes('+') && !normalized.match(/-\d{2}:\d{2}$/)) {
- normalized += 'Z';
- }
- const d = new Date(normalized);
- return isNaN(d.getTime()) ? null : d;
- }
- /**
- * 判断当前资产是否处于冷却锁定中 (next_use_time > now)
- */
- export function isItemInCooldown(nextUseTime?: string | Date | null, nowMs: number = Date.now()): boolean {
- const targetDate = parseUtcDate(nextUseTime);
- if (!targetDate) return false;
- return targetDate.getTime() > nowMs;
- }
- /**
- * 计算剩余冷却时间格式化字符串 (例如: 1h20m, 14m32s, 45s),若已过期则返回 null
- */
- export function getCooldownRemainingTime(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
- const targetDate = parseUtcDate(nextUseTime);
- if (!targetDate) return null;
- const diffMs = targetDate.getTime() - nowMs;
- if (diffMs <= 0) return null;
- const diffSec = Math.floor(diffMs / 1000);
- const m = Math.floor(diffSec / 60);
- const s = diffSec % 60;
- const h = Math.floor(m / 60);
- const d = Math.floor(h / 24);
- if (d > 0) {
- return `${d}d${h % 24}h`;
- }
- if (h > 0) {
- return `${h}h${m % 60}m`;
- }
- if (m > 0) {
- return `${m}m${s}s`;
- }
- return `${s}s`;
- }
- /**
- * 详细中文剩余时间 (用于抽屉详情等场景)
- */
- export function getCooldownRemainingText(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
- const targetDate = parseUtcDate(nextUseTime);
- if (!targetDate) return null;
- const diffMs = targetDate.getTime() - nowMs;
- if (diffMs <= 0) return null;
- const diffSec = Math.floor(diffMs / 1000);
- const m = Math.floor(diffSec / 60);
- const s = diffSec % 60;
- const h = Math.floor(m / 60);
- const d = Math.floor(h / 24);
- if (d > 0) {
- return `${d}天${h % 24}小时`;
- }
- if (h > 0) {
- return `${h}小时${m % 60}分`;
- }
- if (m > 0) {
- return `${m}分${s}秒`;
- }
- return `${s}秒`;
- }
|