import { ColumnType, DateFormat, ITypeOptions, Language, TimeFormat, } from '../../../types'; import { exhaustiveSwitch } from '../../../typeUtils'; import format from 'date-fns/format'; import parseISO from 'date-fns/parseISO'; export const transformDatetimeToString = ( value: string | number, typeOptions: Pick< ITypeOptions, 'includeTime' | 'timeFormat' | 'dateFormat' >, locale?: Language ) => { if (!value) return ''; const dateFormatString = (() => { switch (typeOptions.dateFormat) { case DateFormat.FRIENDLY: if (locale === Language.en) { return 'MMM do, yyyy'; } else { return 'yyyy年M月d日'; } case DateFormat.ISO: return 'yyyy-MM-dd'; case DateFormat.SLASH: return 'yyyy/MM/dd'; case DateFormat.LOCAL: case DateFormat.FORMULA_PARSE_FORMAT: return 'MM/dd/yyyy'; default: { return exhaustiveSwitch({ switchValue: typeOptions.dateFormat, returnValue: 'MM/dd/yyyy', }); } } })(); // Date time value may be a date string or a timestamp const parsedValue = typeof value === 'number' ? value : parseISO(value); const datePart = format(parsedValue, dateFormatString); if (!typeOptions.includeTime) return datePart; const timePart = format( parsedValue, typeOptions.timeFormat === TimeFormat.TWELVE_HOUR ? 'h:mm aaa' : 'HH:mm' ); return `${datePart} ${timePart}`; };