import { DateType } from "react-native-ui-datepicker"; /** * Transforms "YYYY-MM-DD" to "DD/MM/YYYY" * @param dateStr string in ISO date format "YYYY-MM-DD" * @returns formatted string "DD/MM/YYYY" */ export const formatDate = (dateStr: string | null | undefined): string => { if (!dateStr) return ''; const [year, month, day] = dateStr.split('-'); return `${day}/${month}/${year}`; }; /** * Transforms time from "HH:MM:SS" to "HH:MM" * @param timeStr string in time format "HH:MM:SS" * @returns formatted string "HH:MM" */ export const formatTime = (timeStr: string | null | undefined): string => { if (!timeStr) return ''; const [hours, minutes] = timeStr.split(':'); return `${hours}:${minutes}`; }; /** * Formats a date for use with a date picker, normalizing it to midnight * @param d Date in DateType format * @returns string in "YYYY-MM-DD" format or null if input is null/undefined */ export const formatPickerDate = (d: DateType | null | undefined) => { if (!d) return null; const date = new Date(d as string | number | Date); const normalized = new Date(date.getFullYear(), date.getMonth(), date.getDate()); const yyyy = normalized.getFullYear(); const mm = String(normalized.getMonth() + 1).padStart(2, "0"); const dd = String(normalized.getDate()).padStart(2, "0"); return `${yyyy}-${mm}-${dd}`; } /** * Transforms a timestamp into a string "DD/MM/YYYY HH:mm:ss" * @param timestamp string or Date object * @returns formatted string or empty string if input is invalid */ export const formatTimestamp = (timestamp: string | Date | null | undefined): string => { if (!timestamp) return ''; const date = timestamp instanceof Date ? timestamp : new Date(timestamp); if (isNaN(date.getTime())) return ''; const dd = String(date.getDate()).padStart(2, '0'); const mm = String(date.getMonth() + 1).padStart(2, '0'); // months from 0 to 11 const yyyy = date.getFullYear(); const hh = String(date.getHours()).padStart(2, '0'); const min = String(date.getMinutes()).padStart(2, '0'); const ss = String(date.getSeconds()).padStart(2, '0'); return `${dd}/${mm}/${yyyy} ${hh}:${min}:${ss}`; }; /** * Converts an ISO timestamp to a Date object * @param dateStr string in ISO date format * @returns corresponding Date object */ export const parseTimestamp = (dateStr: string | undefined | null): Date => { if (!dateStr) return new Date(); const date = new Date(dateStr); if (isNaN(date.getTime())) return new Date(); return date; }; export const parseSecondsToTime = (totalSeconds: number | null | undefined): string => { if (totalSeconds == null || isNaN(totalSeconds)) return ''; const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; const hh = String(hours); const mm = String(minutes).padStart(2, '0'); const ss = String(seconds).padStart(2, '0'); return `${hh}h`; }