Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created September 19, 2024 14:30
Show Gist options
  • Save ali-master/cc2053eb670b1e12dad2941ae1606b46 to your computer and use it in GitHub Desktop.
Save ali-master/cc2053eb670b1e12dad2941ae1606b46 to your computer and use it in GitHub Desktop.
Javascript human time converter
export type TimeSpanUnit = "ms" | "s" | "m" | "h" | "d" | "w";
export class TimeSpan {
constructor(value: number, unit: TimeSpanUnit) {
this.value = value;
this.unit = unit;
}
public value: number;
public unit: TimeSpanUnit;
public milliseconds(): number {
if (this.unit === "ms") {
return this.value;
}
if (this.unit === "s") {
return this.value * 1000;
}
if (this.unit === "m") {
return this.value * 1000 * 60;
}
if (this.unit === "h") {
return this.value * 1000 * 60 * 60;
}
if (this.unit === "d") {
return this.value * 1000 * 60 * 60 * 24;
}
return this.value * 1000 * 60 * 60 * 24 * 7;
}
public seconds(): number {
return this.milliseconds() / 1000;
}
public transform(x: number): TimeSpan {
return new TimeSpan(Math.round(this.milliseconds() * x), "ms");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment