import { date as formatDate } from '@planningcenter/datetime-fmt' import dayjs from './dayjs' export type DateProps = string | number | Date export function formatDatePreview(date?: DateProps) { if (!date) return '' const now = dayjs() const isToday = now.isSame(date, 'day') const isThisWeek = now.isSame(date, 'week') const isThisYear = now.isSame(date, 'year') if (isToday) return dayjs(date).format('h:mma') if (isThisWeek) return formatDate(date, { style: 'relative-short' }) if (isThisYear) return formatDate(date, { style: 'abbreviated' }) // TODO: Org date format return formatShorterDate(date) } const formatShorterDate = (date: DateProps) => { // Drop the century from the year return formatDate(date, { style: 'short', year: true }).replace(/20(\d{2})/, '$1') } export function getRelativeDateStatus(date: DateProps) { const now = dayjs() const isToday = now.isSame(date, 'day') const isThisWeek = now.isSame(date, 'week') const isThisYear = now.isSame(date, 'year') return { isToday, isThisWeek, isThisYear } } export function relativeDateTime(dateTimeString: string): string { const date = new Date(dateTimeString) const now = new Date() const isToday = date.toDateString() === now.toDateString() const isThisYear = date.getFullYear() === now.getFullYear() if (isToday) { return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }) } else if (isThisYear) { return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) } else { return date.toLocaleDateString('en-US') } } export function relativeTime(date: DateProps): string { const now = dayjs() const then = dayjs(date) const duration = dayjs.duration(now.diff(then)) if (duration.asDays() < 1) { return then.fromNow() } else { return dayjs(date).format('h:mma') } } export function formatEventDateTime(date: DateProps) { const { isThisYear } = getRelativeDateStatus(date) const local = dayjs(date) const day = local.format(isThisYear ? 'MMM D' : 'MMM D, YYYY') const time = local.format(local.minute() === 0 ? 'ha' : 'h:mma') return `${day} at ${time}` }