add Time test
This commit is contained in:
+27
-29
@@ -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(" ");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user