Files
techtracker/src/lib/utils.ts
2025-09-08 11:25:57 -05:00

58 lines
1.4 KiB
TypeScript

import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { type Timestamp } from '@/lib/types';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export const ccn = ({
context,
className,
on = '',
off = '',
}: {
context: boolean;
className: string;
on: string;
off: string;
}) => {
return twMerge(className, context ? on : off);
};
const toDate = (ts: Timestamp): Date | null => {
if (ts instanceof Date) return isNaN(ts.getTime()) ? null : ts;
if (typeof ts === 'number') {
// Heuristic: treat small numbers as seconds
const ms = ts < 1_000_000_000_000 ? ts * 1000 : ts;
const d = new Date(ms);
return isNaN(d.getTime()) ? null : d;
}
// string: try numeric first, then ISO/date string
const asNum = Number(ts);
const d =
Number.isFinite(asNum) && asNum !== 0 ? toDate(asNum) : new Date(ts);
return d && !isNaN(d.getTime()) ? d : null;
};
export const formatTime = (timestamp: Timestamp, locale = 'en-US'): string => {
const date = toDate(timestamp);
if (!date) return '--:--';
return date.toLocaleTimeString(locale, {
hour: 'numeric',
minute: 'numeric',
});
};
export const formatDate = (timestamp: Timestamp, locale = 'en-US'): string => {
const date = toDate(timestamp);
if (!date) return '--/--';
return date.toLocaleDateString(locale, {
month: 'long',
day: 'numeric',
});
};