54 lines
2.2 KiB
JavaScript
54 lines
2.2 KiB
JavaScript
export class TimeSpan {
|
|
start;
|
|
end;
|
|
timeZone;
|
|
constructor(timeSpanStr, timeZone) {
|
|
const [startStr, endStr] = timeSpanStr.split("-");
|
|
this.start = this.parseTime(startStr);
|
|
this.end = this.parseTime(endStr);
|
|
this.timeZone = timeZone;
|
|
}
|
|
parseTime(timeStr) {
|
|
const [hours, minutes] = timeStr.split(":").map(Number);
|
|
return { hours, minutes };
|
|
}
|
|
contains(timestamp = Date.now()) {
|
|
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 function calculateSecondsBetween(start, end) {
|
|
const seconds = Math.max(60, (end - start) / 1000);
|
|
return {
|
|
seconds,
|
|
toReadable: (roundToMinutes) => secondsToReadable(seconds, roundToMinutes),
|
|
};
|
|
}
|
|
export function secondsToReadable(secs, roundToMinutes = false) {
|
|
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*$/, "");
|
|
}
|