81 lines
2.3 KiB
TypeScript
81 lines
2.3 KiB
TypeScript
export class TimeSpan {
|
|
private start: { hours: number; minutes: number };
|
|
private end: { hours: number; minutes: number };
|
|
private timeZone;
|
|
|
|
constructor(timeSpanStr: string, timeZone: string) {
|
|
const [startStr, endStr] = timeSpanStr.split("-");
|
|
this.start = this.parseTime(startStr);
|
|
this.end = this.parseTime(endStr);
|
|
this.timeZone = timeZone;
|
|
}
|
|
|
|
private parseTime(timeStr: string) {
|
|
const [hours, minutes] = timeStr.split(":").map(Number);
|
|
return { hours, minutes };
|
|
}
|
|
|
|
contains(timestamp: number = Date.now()): boolean {
|
|
const date = new Date(timestamp);
|
|
|
|
const berlinTimeStr = date.toLocaleString("de-DE", {
|
|
timeZone: this.timeZone, // "Europe/Berlin"
|
|
hour12: false,
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
});
|
|
|
|
const [hours, minutes] = berlinTimeStr.split(":").map(Number);
|
|
const currentMinutes = hours * 60 + minutes;
|
|
const startMinutes = this.start.hours * 60 + this.start.minutes;
|
|
const endMinutes = this.end.hours * 60 + this.end.minutes;
|
|
|
|
if (startMinutes > endMinutes) {
|
|
return currentMinutes >= startMinutes || currentMinutes < endMinutes;
|
|
} else {
|
|
return currentMinutes >= startMinutes && currentMinutes < endMinutes;
|
|
}
|
|
}
|
|
}
|
|
|
|
export interface TimeBetween {
|
|
seconds: number;
|
|
toReadable: (roundToMinutes?: boolean) => string;
|
|
}
|
|
|
|
export function calculateSecondsBetween(
|
|
start: number,
|
|
end: number,
|
|
): TimeBetween {
|
|
const seconds = Math.max(60, (end - start) / 1000);
|
|
return {
|
|
seconds,
|
|
toReadable: (roundToMinutes?: boolean) =>
|
|
secondsToReadable(seconds, roundToMinutes),
|
|
};
|
|
}
|
|
|
|
export function secondsToReadable(
|
|
secs: number,
|
|
roundToMinutes: boolean = false,
|
|
): string {
|
|
const totalSeconds = roundToMinutes ? Math.round(secs / 60) * 60 : secs;
|
|
|
|
var days = Math.floor(totalSeconds / (3600 * 24));
|
|
var hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
|
|
var minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
var seconds = Math.floor(totalSeconds % 60);
|
|
|
|
var dayDisplay = days > 0 ? days + (days === 1 ? " day, " : " days, ") : "";
|
|
var hourDisplay =
|
|
hours > 0 ? hours + (hours === 1 ? " hour, " : " hours, ") : "";
|
|
var minuteDisplay =
|
|
minutes > 0 ? minutes + (minutes === 1 ? " minute, " : " minutes, ") : "";
|
|
var secondDisplay =
|
|
seconds > 0 ? seconds + (seconds === 1 ? " second" : " seconds") : "";
|
|
return (dayDisplay + hourDisplay + minuteDisplay + secondDisplay).replace(
|
|
/,\s*$/,
|
|
"",
|
|
);
|
|
}
|