tweak getDurationFromTimestamps for i18n and abbreviations

This commit is contained in:
Josh Hawkins 2025-10-23 21:48:02 -05:00
parent 6e765738ce
commit f257125fde

View File

@ -1,6 +1,7 @@
import { fromUnixTime, intervalToDuration, formatDuration } from "date-fns";
import { Locale } from "date-fns/locale";
import { formatInTimeZone } from "date-fns-tz";
import i18n from "@/utils/i18n";
export const longToDate = (long: number): Date => new Date(long * 1000);
export const epochToLong = (date: number): number => date / 1000;
export const dateToLong = (date: Date): number => epochToLong(date.getTime());
@ -234,11 +235,13 @@ export const formatUnixTimestampToDateTime = (
* If end time is not provided, it returns 'In Progress'
* @param start_time: number - Unix timestamp for start time
* @param end_time: number|null - Unix timestamp for end time
* @param abbreviated: boolean - Whether to use abbreviated forms (h, m, s) instead of full words
* @returns string - duration or 'In Progress' if end time is not provided
*/
export const getDurationFromTimestamps = (
start_time: number,
end_time: number | null,
abbreviated: boolean = false,
): string => {
if (isNaN(start_time)) {
return "Invalid start time";
@ -250,12 +253,39 @@ export const getDurationFromTimestamps = (
}
const start = fromUnixTime(start_time);
const end = fromUnixTime(end_time);
duration = formatDuration(intervalToDuration({ start, end }), {
format: ["hours", "minutes", "seconds"],
})
.replace("hours", "h")
.replace("minutes", "m")
.replace("seconds", "s");
const durationObj = intervalToDuration({ start, end });
// Build duration string using i18n keys or abbreviations
const parts: string[] = [];
if (durationObj.hours) {
const count = durationObj.hours;
if (abbreviated) {
parts.push(`${count}h`);
} else {
const key = count === 1 ? "hour_one" : "hour_other";
parts.push(i18n.t(`time.${key}`, { time: count, ns: "common" }));
}
}
if (durationObj.minutes) {
const count = durationObj.minutes;
if (abbreviated) {
parts.push(`${count}m`);
} else {
const key = count === 1 ? "minute_one" : "minute_other";
parts.push(i18n.t(`time.${key}`, { time: count, ns: "common" }));
}
}
if (durationObj.seconds) {
const count = durationObj.seconds;
if (abbreviated) {
parts.push(`${count}s`);
} else {
const key = count === 1 ? "second_one" : "second_other";
parts.push(i18n.t(`time.${key}`, { time: count, ns: "common" }));
}
}
duration = parts.join(" ");
}
return duration;
};