add Time test

This commit is contained in:
Timi
2026-04-11 09:47:05 +08:00
parent 26e533dc69
commit 6735a815c4
5 changed files with 99 additions and 34 deletions
+27 -29
View File
@@ -71,26 +71,6 @@ export default class Time {
}
}
/**
* 将毫秒值转换为可读的时间字符串
*
* @param ms 毫秒值
* @return 时间字符串,如 "10 天"、"5 小时"、"30 分钟"、"15 秒"、"500 毫秒"
*/
public static toString(ms: number): string {
if (Time.D <= ms) {
return `${Math.floor(ms / Time.D)}`;
} else if (Time.H <= ms) {
return `${Math.floor(ms / Time.H)} 小时`;
} else if (Time.M <= ms) {
return `${Math.floor(ms / Time.M)} 分钟`;
} else if (Time.S <= ms) {
return `${Math.floor(ms / Time.S)}`;
} else {
return `${Math.floor(ms)} 毫秒`;
}
}
public static between(begin: Date, end?: Date) : any {
if (!end) {
end = new Date();
@@ -106,18 +86,36 @@ export default class Time {
return { l, y, d, h, m, s, ms };
}
public static duration(begin?: number, ms?: boolean): string {
if (!begin) {
public static duration(totalMs?: number, ms?: boolean): string {
if (!totalMs) {
return "";
}
const r = Time.between(new Date(begin), new Date());
let remain = Math.floor(totalMs);
const yearMs = Time.D * 365;
const dayMs = Time.D;
const hourMs = Time.H;
const minuteMs = Time.M;
const secondMs = Time.S;
const years = Math.floor(remain / yearMs);
remain %= yearMs;
const days = Math.floor(remain / dayMs);
remain %= dayMs;
const hours = Math.floor(remain / hourMs);
remain %= hourMs;
const minutes = Math.floor(remain / minuteMs);
remain %= minuteMs;
const seconds = Math.floor(remain / secondMs);
remain %= secondMs;
const milliseconds = remain;
const parts: string[] = [];
Toolkit.doWhere(0 < r.y, () => parts.push(`${r.y}`));
Toolkit.doWhere(0 < r.d, () => parts.push(`${r.d} `));
Toolkit.doWhere(0 < r.h, () => parts.push(`${r.h} 小时`));
Toolkit.doWhere(0 < r.m, () => parts.push(`${r.m} 分钟`));
Toolkit.doWhere(0 < r.s, () => parts.push(`${r.s}`));
Toolkit.doWhere(!!ms && 0 < r.ms, () => parts.push(`${r.ms} 毫秒`));
Toolkit.doWhere(0 < years, () => parts.push(`${years}`));
Toolkit.doWhere(0 < days, () => parts.push(`${days} `));
Toolkit.doWhere(0 < hours, () => parts.push(`${hours} 小时`));
Toolkit.doWhere(0 < minutes, () => parts.push(`${minutes} 分钟`));
Toolkit.doWhere(0 < seconds, () => parts.push(`${seconds}`));
Toolkit.doWhere(!!ms && 0 < milliseconds, () => parts.push(`${milliseconds} 毫秒`));
return parts.join(" ");
}