目录— 个文件
⌕
目录加载中…
…/core/utility/UtilityTime.ts
1import { Component } from "cc";
2
3
4/**
5 * 时间格式枚举
6 */
7export enum TimeFormat {
8 MS_1 = 1, //6m6s
9 MS_2, //00:00
10 S, //60s
11}
12/**
13 * 时间工具类
14 * 2026-6-16 新增异步智能队列方法和异步同步方法
15 */
16export class UtilityTime {
17 /** 一天包含的毫秒数,供需要按自然日计算的系统统一使用。 */
18 public static readonly MILLISECONDS_PER_DAY: number = 24 * 60 * 60 * 1000;
19
20 /** 每日玩法统一按北京时间(UTC+8)零点换日,不随设备时区变化。 */
21 private static readonly gameTimezoneMs: number = 8 * 3600000;
22
23 /** 游戏日编号用于跨天比较;时间戳单位为毫秒。 */
24 public static GetGameDay(timestamp: number): number {
25 return Math.floor((timestamp + this.gameTimezoneMs) / this.MILLISECONDS_PER_DAY);
26 }
27
28 /** 计算下一次北京时间零点距当前的毫秒数。 */
29 public static GetTimeToNextGameDay(timestamp: number): number {
30 return (this.GetGameDay(timestamp) + 1) * this.MILLISECONDS_PER_DAY - this.gameTimezoneMs - timestamp;
31 }
32
33 /**
34 * 获取当前时间戳
35 */
36 public static GetCurrentTimeStamp(): number {
37 return Date.now();
38 }
39
40 /** 将时间戳转换为北京时间日期,保存格式仍为 YYYY-MM-DD。 */
41 public static GetGameDateStr(timestamp: number): string {
42 return new Date(timestamp + this.gameTimezoneMs).toISOString().slice(0, 10);
43 }
44
45 /**
46 * 获取时间字符串
47 * @param ms 时间毫秒数
48 * @param format 时间格式
49 * @returns 时间字符串
50 */
51 public static GetTimeStr(s: number, format: TimeFormat = TimeFormat.MS_1): string {
52 const minutes = Math.floor(s / 60);
53 const remainingSeconds = Math.floor(s % 60);
54 switch (format) {
55 case TimeFormat.MS_1:
56 return `${minutes}m${remainingSeconds}s`;
57 case TimeFormat.MS_2:
58 let minutesStr: string = minutes < 10 ? `0${minutes}` : `${minutes}`;
59 let remainingSecondsStr: string = remainingSeconds < 10 ? `0${remainingSeconds}` : `${remainingSeconds}`;
60 return `${minutesStr}:${remainingSecondsStr}`;
61 case TimeFormat.S:
62 let seconds = Math.floor(s);
63 return `${seconds}`;
64 }
65 return '';
66 }
67
68 /**
69 * 为 URL 添加时间戳参数,避免缓存
70 * @param url 原始 URL
71 * @returns 带时间戳的新 URL
72 */
73 public static AddTimestampToUrl(url: string): string {
74 const timestamp = Date.now(); // 获取当前毫秒级时间戳
75 // 检查 URL 是否已有查询参数,避免重复添加 ?
76 return url.includes('?')
77 ? `${url}&t=${timestamp}` // 已有参数时用 & 拼接
78 : `${url}?t=${timestamp}`; // 无参数时用 ? 拼接
79 }
80
81 /** 等待 (单位:ms) */
82 static wait(ms: number, target?: Component) {
83 return new Promise(rs => {
84 if (target) {
85 return target.scheduleOnce(rs, ms / 1000);
86 }
87 else {
88 setTimeout(rs, ms);
89 }
90 })
91 }
92
93 static waitFrame(frame: number = 1): Promise<void> {
94 return new Promise(rs => {
95 let finished = 0;
96 let wait = function () {
97 requestAnimationFrame(() => {
98 if (++finished >= frame) {
99 rs();
100 }
101 else {
102 wait()
103 }
104 })
105 }
106 wait();
107 })
108 }
109 /**按钮等待,给按钮加入按下间隔,防止重复点击,返回为true时不能点击*/
110 private static _canTouch: any = {};
111 static buttonWait(key = 'btn', _time = 300): boolean {
112 if (key in UtilityTime._canTouch) {
113 return true;
114 }
115 UtilityTime._canTouch[key] = true;
116 setTimeout(() => {
117 delete UtilityTime._canTouch[key];
118 }, _time);
119 return false;
120 }
121 private static _soloKeys: string[] = [];
122 /**
123 * 【不可同时重复执行方法】
124 * @param _func 要执行的方法
125 * @param _key 设置不可重复执行的方法key,相同key同一时间不可重复执行
126 * @returns 返回原方法的回调
127 */
128 static async soloFunction<T extends Function>(_func: T, _key = "normal") {
129 if (this._soloKeys.indexOf(_key) > -1) {
130 return false;
131 }
132 this._soloKeys.push(_key);
133 let _r = await _func();
134 let _idx = this._soloKeys.indexOf(_key);
135 if (_idx > -1) {
136 this._soloKeys.splice(_idx, 1)
137 }
138 return _r;
139
140 }
141
142
143
144 private static _sequenceFunctionGrop: { [groupId: string]: { inExecute: boolean, funcs: Function[] } } = {};
145 /**
146 * 【顺序执行方法】
147 * 所有同组的方法按放入的顺序全部顺序执行
148 * @param groupId
149 * @param func
150 */
151 static sequenceFunction(groupId: string, func: Function) {
152 if (!this._sequenceFunctionGrop[groupId]) {
153 this._sequenceFunctionGrop[groupId] = { inExecute: false, funcs: [] };
154 }
155 const funcData = this._sequenceFunctionGrop[groupId];
156 funcData.funcs.push(func);
157 this._executeSequenceFunction(groupId);
158
159 }
160 // 顺序执行逻辑
161 private static async _executeSequenceFunction(groupId: string) {
162 const funcData = this._sequenceFunctionGrop[groupId];
163 if (!funcData) {
164 return;
165 }
166 if (funcData.inExecute) {
167 return;
168 }
169 const curFunc = funcData.funcs.shift()!;
170 funcData.inExecute = true;
171 await curFunc();
172 funcData.inExecute = false;
173 if (funcData.funcs.length > 0) {
174 this._executeSequenceFunction(groupId);
175 }
176 else {
177 funcData.inExecute = false;
178 }
179 }
180
181
182}
讲解183 行
时间与异步流程工具人工通读
UtilityTime.ts
以北京时间为基准提供游戏日编号、跨天剩余毫秒和日期字符串,另含秒数转时长文本与 URL 防缓存参数。还提供基于 Promise 的等待、按钮防连点、同键互斥执行与同组顺序执行等流程控制。
先读 GetGameDay 与 GetTimeToNextGameDay 的时区换算,再看 GetTimeStr 的秒单位,最后读 wait、buttonWait、soloFunction、sequenceFunction。
特殊处理与易错点
- 时区gameTimezoneMs 固定加 8 小时,游戏日与日期字符串都按北京时间零点换日,不受设备时区影响。L21
- 易错点GetTimeStr 的形参注释写毫秒,实际按秒处理,传毫秒会得到放大约一千倍的分钟数。L51
- 边界buttonWait 返回 true 表示处于冷却不可点击,语义与常见的 canXxx 相反。L111
- 易错点soloFunction 中被执行方法抛错时不会从 _soloKeys 移除 key,该 key 会一直锁死。L128
- 设计sequenceFunction 依靠 inExecute 标志和队列递归实现串行,函数抛错会中断整条队列。L161
7注释时间格式枚举
16注释UtilityTime:时间工具类 2026-6-16 新增异步智能队列方法和异步同步方法
18注释一天包含的毫秒数,供需要按自然日计算的系统统一使用。
21注释每日玩法统一按北京时间(UTC+8)零点换日,不随设备时区变化。
24方法把毫秒时间戳加上 8 小时偏移后除以一天毫秒数并向下取整,得到北京时间为准的游戏日编号。
29方法用游戏日编号加一算出下个零点,再减去当前时间戳,得到距换日的剩余毫秒。
36方法直接返回 Date.now 得到的毫秒级时间戳。
41方法时间戳加 8 小时后转 ISO 字符串并截取前十位,得到北京时间的年月日。
51方法把秒数拆成分钟与秒,按三种枚举格式分别输出带后缀文本、补零分秒或纯秒数。
73方法按 URL 是否已含问号,用与号或问号追加当前毫秒时间戳参数 t。
76注释检查 URL 是否已有查询参数,避免重复添加 ?
82方法返回 Promise,传入组件时把毫秒换算成秒交给 scheduleOnce,否则用 setTimeout …
93方法用 requestAnimationFrame 逐帧计数,累计到指定帧数后 resolve。
110注释按钮等待,给按钮加入按下间隔,防止重复点击,返回为true时不能点击
111方法key 已在冷却表中就返回 true,否则登记并在指定毫秒后删除,返回 false。
128方法key 正在执行时直接返回 false,否则登记 key、等待方法完成,再移除 key 并返回结果。
151方法把函数推入同组队列并触发串行执行,已有函数执行中时只入队不立即运行。
161方法取出队首函数置为执行中,等待其完成后清除标志,还有剩余就递归继续。