// composables/usePersianTimeAgo.ts import { formatDistance } from "date-fns-jalali"; import { faIR } from "date-fns-jalali/locale"; import { Jalali } from "jalali-ts"; const toGregorianDate = (input: Date | string): Date | null => { if (input instanceof Date) { return isNaN(input.getTime()) ? null : input; } if (typeof input !== "string" || !input) return null; const yearStr = input.slice(0, 4); const year = Number(yearStr); // jDateTimeField from django_jalali serializes with the Jalali year // (typically 13XX or 14XX). Anything below ~1700 is treated as Jalali // and converted to the equivalent Gregorian moment via jalali-ts. // date-fns-jalali's parseISO can't be used here — it parses the year // numerically without calendar conversion. if (!Number.isNaN(year) && year < 1700) { try { return Jalali.parse(input).date; } catch { return null; } } const native = new Date(input); return isNaN(native.getTime()) ? null : native; }; export function usePersianTimeAgo(date: Date | string) { const timeAgo = ref(""); const updateTimeAgo = () => { const parsed = toGregorianDate(date); if (!parsed) { timeAgo.value = ""; return; } timeAgo.value = formatDistance(parsed, new Date(), { addSuffix: true, locale: faIR, }); }; onMounted(() => { updateTimeAgo(); const interval = setInterval(updateTimeAgo, 60000); onUnmounted(() => clearInterval(interval)); }); return timeAgo; }