import { DateType } from "react-native-ui-datepicker"; /** * Trasforma una data da "YYYY-MM-DD" a "DD/MM/YYYY" * @param dateStr stringa data in formato ISO "YYYY-MM-DD" * @returns stringa formattata "DD/MM/YYYY" */ export const formatDate = (dateStr: string | null | undefined): string => { if (!dateStr) return ''; const [year, month, day] = dateStr.split('-'); return `${day}/${month}/${year}`; }; /** * Trasforma un'ora da "HH:MM:SS" a "HH:MM" * @param timeStr stringa ora in formato "HH:MM:SS" * @returns stringa formattata "HH:MM" */ export const formatTime = (timeStr: string | null | undefined): string => { if (!timeStr) return ''; const [hours, minutes] = timeStr.split(':'); return `${hours}:${minutes}`; }; /** * Formatta una data per l'uso con un date picker, normalizzandola a mezzanotte * @param d Data in formato DateType * @returns stringa data in formato "YYYY-MM-DD" o null se l'input รจ 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}`; } /** * Trasforma un timestamp in stringa "DD/MM/YYYY HH:mm:ss" * @param timestamp stringa o oggetto Date * @returns stringa formattata oppure vuota se input non valido */ 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'); // mesi da 0 a 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}`; }; /** * Converte un timestamp ISO in oggetto Date * @param dateStr stringa data in formato ISO * @returns oggetto Date corrispondente */ 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`; }