UNPKG

@cranberry-money/shared-utils

Version:

Shared utility functions for Blueberry platform

100 lines 3.08 kB
import { TIME_RANGES } from '@cranberry-money/shared-constants'; /** * Format a date string for display (e.g., "8 January 2026"). * Unified function for use across all projects. */ export function formatDate(dateString, fallback = 'Never', locale = 'en-AU') { if (!dateString) return fallback; try { return new Date(dateString).toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric', }); } catch { return dateString; } } /** * Format a date string to short format (e.g., "Jan 8"). */ export function formatShortDate(dateString, fallback = 'Never', locale = 'en-AU') { if (!dateString) return fallback; try { return new Date(dateString).toLocaleDateString(locale, { month: 'short', day: 'numeric' }); } catch { return dateString; } } /** * Format a date string to time only (e.g., "14:30"). */ export function formatTime(dateString, fallback = 'Never', locale = 'en-AU') { if (!dateString) return fallback; try { return new Date(dateString).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: false }); } catch { return dateString; } } /** * Format a date string with date and time (e.g., "Jan 8, 2026, 14:30"). */ export function formatDateTime(dateString, fallback = 'Never', locale = 'en-AU') { if (!dateString) return fallback; try { return new Date(dateString).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', }); } catch { return dateString; } } export function getDateRange(timeRange) { if (timeRange === 'ALL') return { start_date: undefined, end_date: undefined }; const range = TIME_RANGES.find((r) => r.label === timeRange); if (!range?.months) return { start_date: undefined, end_date: undefined }; const endDate = new Date(); const startDate = new Date(); startDate.setMonth(startDate.getMonth() - range.months); return { start_date: startDate.toISOString().split('T')[0], end_date: endDate.toISOString().split('T')[0] }; } /** * Parse a YYYY-MM-DD date string into a Date object. * Returns undefined if the string is empty or invalid. */ export function parseDateString(dateString) { if (!dateString) return undefined; const [year, month, day] = dateString.split('-').map(Number); if (!year || !month || !day) return undefined; return new Date(year, month - 1, day); } /** * Format a Date object to a YYYY-MM-DD string. * Returns an empty string if the date is undefined. */ export function formatDateToString(date) { if (!date) return ''; const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } //# sourceMappingURL=date.js.map