| 1 |
import { format, formatISO, isValid, parseISO } from 'date-fns'; |
| 2 |
|
| 3 |
/** |
| 4 |
* Parses a date value from a string or Date object. |
| 5 |
* Returns null if the value is falsy or results in an invalid date. |
| 6 |
* |
| 7 |
* @param {string | Date | null | undefined} value - ISO string or Date object to parse |
| 8 |
* @returns {Date | null} Parsed Date object, or null if invalid |
| 9 |
*/ |
| 10 |
export function parseDate(value) { |
| 11 |
if (!value) return null; |
| 12 |
const date = typeof value === 'string' ? parseISO(value) : new Date(value); |
| 13 |
return isValid(date) ? date : null; |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Formats a date value for display in the trigger button. |
| 18 |
* Uses the format: "dd/MM/yyyy, hh:mm AM/PM" (e.g. "04/06/2026, 02:30 PM"). |
| 19 |
* |
| 20 |
* @param {string | Date | null | undefined} value - ISO string or Date object to format |
| 21 |
* @returns {string} Formatted date string, or empty string if invalid |
| 22 |
*/ |
| 23 |
export function formatDisplay(value) { |
| 24 |
const date = parseDate(value); |
| 25 |
if (!date) return ''; |
| 26 |
return format(date, 'dd/MM/yyyy, hh:mm aa'); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Extracts 12-hour time parts from a date value. |
| 31 |
* Defaults to current time if the value is empty or invalid. |
| 32 |
* |
| 33 |
* @param {string | Date | null | undefined} value - ISO string or Date object |
| 34 |
* @returns {{ hour: number, minute: number, period: 'AM' | 'PM' }} |
| 35 |
*/ |
| 36 |
export function get12HourParts(value) { |
| 37 |
const date = parseDate(value) || new Date(); |
| 38 |
let h = date.getHours(); |
| 39 |
const m = date.getMinutes(); |
| 40 |
const period = h >= 12 ? 'PM' : 'AM'; |
| 41 |
h = h % 12 || 12; |
| 42 |
return { hour: h, minute: m, period }; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Converts a 12-hour format hour and period to 24-hour format. |
| 47 |
* |
| 48 |
* @param {number} hour - Hour in 12-hour format (1-12) |
| 49 |
* @param {'AM' | 'PM'} period - AM or PM |
| 50 |
* @returns {number} Hour in 24-hour format (0-23) |
| 51 |
*/ |
| 52 |
export function to24Hour(hour, period) { |
| 53 |
if (period === 'AM') return hour === 12 ? 0 : hour; |
| 54 |
return hour === 12 ? 12 : hour + 12; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Builds an ISO 8601 date string from a day, 12-hour time parts. |
| 59 |
* Falls back to the current date/time if day is falsy. |
| 60 |
* |
| 61 |
* @param {Date | null} day - The date to use |
| 62 |
* @param {number} hour - Hour in 12-hour format (1-12) |
| 63 |
* @param {number} minute - Minute (0-59) |
| 64 |
* @param {'AM' | 'PM'} period - AM or PM |
| 65 |
* @returns {string} ISO 8601 formatted date string |
| 66 |
*/ |
| 67 |
export function buildDate(day, hour, minute, period) { |
| 68 |
const date = new Date(day || new Date()); |
| 69 |
date.setHours(to24Hour(hour, period), minute, 0, 0); |
| 70 |
return formatISO(date); |
| 71 |
} |
| 72 |
|