UNPKG

@cerberus-design/react

Version:

The Cerberus Design React component library.

105 lines (104 loc) 2.44 kB
// src/hooks/useDate.ts import { useState, useCallback, useMemo } from "react"; function useDate(options) { const initialValue = options?.initialValue ?? ""; const format = options?.format ?? DateFormats.USMilitary; const onChange = options?.onChange; const [value, setValue] = useState(initialValue); const handleChange = useCallback( (e) => { const newValue = formatMilitaryDate(e.currentTarget.value); if (onChange) onChange(e); setValue(newValue); }, [onChange] ); return useMemo( () => ({ format, value, ISO: formatMilitaryToISO(value), onChange: handleChange }), [format, value, handleChange] ); } function formatMilitaryToISO(input) { const [day, month, year] = input.split(" "); const monthIndex = MONTHS.findIndex((m) => m.startsWith(month)); const monthNum = monthIndex + 1; return `${year ?? "0000"}-${monthNum.toString().padStart(2, "0")}-${day.padStart( 2, "0" )}`; } function formatMilitaryDate(input) { let formatted = input.toUpperCase().replace(/[^0-9A-Z]/g, ""); let day = ""; let month = ""; let year = ""; if (formatted.length >= 2) { day = formatted.replace(/[^0-9]/g, "").slice(0, 2); const dayNum = parseInt(day, 10); if (dayNum > 31) day = "31"; else if (dayNum === 0) day = "01"; formatted = formatted.slice(2); } if (formatted.length >= 3) { month = formatted.slice(0, 3); const monthIndex = MONTHS.findIndex((m) => m.startsWith(month)); if (monthIndex !== -1) { month = MONTHS[monthIndex]; } else { month = month.replace(/[^A-Z]/g, ""); } formatted = formatted.slice(3); } if (formatted.length > 0) { year = formatted.slice(0, 4); } return [day, month, year].filter(Boolean).join(" "); } function formatISOToMilitary(date) { const [year, month, day] = date.split("-"); const monthIndex = parseInt(month, 10) - 1; const monthStr = MONTHS[monthIndex]; return `${day} ${monthStr} ${year}`; } var DateFormats = { get ISO() { return "YYYY-MM-DD"; }, get USMilitary() { return "DD MMM YYYY"; }, get Months() { return MONTHS; } }; var MONTHS = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ]; export { useDate, formatMilitaryToISO, formatMilitaryDate, formatISOToMilitary, DateFormats }; //# sourceMappingURL=chunk-MWRO5QYD.js.map