All files / src/utils date.ts

93.18% Statements 287/308
85.45% Branches 94/110
100% Functions 39/39
93.18% Lines 287/308

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 6011x                                         1x 1x     1x             1x   1x     1x           1x 1x 1x   1x 1x                 1x 12x 12x 12x               1x 19x 19x 19x 19x   19x 19x 10x 9x   19x                       1x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x   5x 5x             1x 295x 295x 295x 295x 295x 295x   295x 295x               1x 2x 2x                       1x 7x 7x 7x 7x   4x 7x   7x 7x 7x         1x 9x 9x   9x 9x         1x 9x 9x 9x   1x 1x 1x 1x 1x 1x 1x 1x 3x 3x     3x 3x 3x   3x 3x 1x 3x 3x     3x 3x 3x 3x 3x   3x 3x 1x 3x 3x     3x 3x 3x   3x 3x 1x               1x 10x 10x                                         1x 23x 23x 23x 23x 23x 6x   23x 5x 5x 5x   23x 6x   23x 23x   23x 23x                               1x 8x 8x 4x 4x   4x 4x 12x 12x 4x 4x                         1x 37x 30x 30x 30x 30x 30x                           1x 7x 7x 7x 7x 7x 7x     7x     7x 7x   3x 3x   3x 3x                           1x 1x 1x 1x 1x 1x   1x   1x                       1x 2x 2x 2x                   1x 5x 5x 5x     5x 5x   2x 2x   2x 2x   1x 1x 1x 1x               1x 320x 320x 320x 2x 2x   320x       320x         318x   320x 69x 69x   320x 169x 169x 169x   158x 5x 5x 5x   75x 320x 320x                     1x 40x 40x 40x       40x       40x         40x 40x 40x                       1x 65x 65x 65x     1x 36x 36x 36x             1x 70x 70x 70x 70x 66x 66x     1x 328x 328x     1x 96x     1x 78x     1x 78x 78x 78x 78x 78x   1x 81x 81x 81x 81x 81x 81x     1x 81x 81x 81x 81x 81x 81x   1x 88x 88x 88x   88x 77x 77x   11x 11x   80x 3x 3x   8x   88x           8x 8x 8x 8x 8x   1x 35x 35x 35x 35x 35x 35x 35x   35x 35x  
import {
  format,
  isAfter,
  setHours,
  setMinutes,
  differenceInCalendarDays,
  startOfDay,
  parse,
  startOfWeek,
  subWeeks,
  subMonths,
  subQuarters,
  subYears,
  startOfMonth,
  startOfQuarter,
  startOfYear,
  isSameDay,
  formatDistanceStrict,
  differenceInSeconds,
  differenceInMinutes,
} from 'date-fns';
import { fromZonedTime, toZonedTime } from 'date-fns-tz';
import { DateTime, Effect } from 'effect';
 
// Constants
import {
  DATE_FORMAT,
  DATE_FORMATS,
  TIME_RANGE_FORMATTER,
} from '@/constants/date';
 
// Types
import { ChartMode } from '@/types/chart';
 
const KITCHEN_TIMEZONE = 'Asia/Ho_Chi_Minh';
 
/** Milliseconds since the Unix epoch; prefer over raw `Date.now()` for tests and single place to stub time. */
export const getNowMs = (): number => Date.now();
 
/**
 * Returns the current year as a number.
 * Useful for dynamically displaying copyright years.
 */
export const getCurrentYear = (): number => {
  const now = Effect.runSync(DateTime.now);
  const parts = DateTime.toPartsUtc(now);
 
  return parts.year;
};
 
/**
 * Format a date string (ISO format) into a readable label.
 * Example: "2025-07-29T00:00:00.000Z" → "Tuesday, July 29th"
 *
 * @param dateStr - The ISO date string to format
 * @returns A formatted date string like "Friday, August 1st"
 */
export const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr);
  return format(date, 'EEEE, MMMM do');
};
 
/**
 * Checks if the given date string represents today.
 *
 * @param dateStr - ISO date string
 * @returns True if the date is today, false otherwise
 */
export const isToday = (dateStr: string): boolean => {
  const nowUtc = Effect.runSync(DateTime.now);
  const now = DateTime.toDate(nowUtc);
  const dateUtc = DateTime.unsafeFromDate(new Date(dateStr));
  const date = DateTime.toDate(dateUtc);
 
  return (
    now.getFullYear() === date.getFullYear() &&
    now.getMonth() === date.getMonth() &&
    now.getDate() === date.getDate()
  );
};
 
/**
 * Checks if a given date is considered expired based on:
 * - It is a past date (before today), AND
 * - The current time has passed a specific cutoff time (default: 11:30 AM local time)
 *
 * @param dateStr - An ISO date string, e.g. "2025-08-01T00:00:00.000Z"
 * @param hour - The cutoff hour (default: 11)
 * @param minute - The cutoff minute (default: 30)
 * @returns true if the date is in the past and the current time is after the cutoff; otherwise false.
 */
export const isExpiredDay = (
  dateStr: string,
  hour = 11,
  minute = 30,
  timeZone = 'Asia/Ho_Chi_Minh',
): boolean => {
  const inputDate = DateTime.toDate(DateTime.unsafeFromDate(new Date(dateStr)));
  const utcNow = DateTime.toDate(Effect.runSync(DateTime.now));
 
  const localNow = toZonedTime(utcNow, timeZone);
  const today = startOfDay(localNow);
  const limitToday = setMinutes(setHours(today, hour), minute);
  const diffInDays = differenceInCalendarDays(localNow, inputDate);
  const isAfterLimitToday = isAfter(localNow, limitToday);
 
  return diffInDays > 1 || (diffInDays === 1 && isAfterLimitToday);
};
 
/**
 * Converts a date string or Date object to an ISO date string (YYYY-MM-DD).
 * @param date A date string or Date object.
 * @returns A string in format 'YYYY-MM-DD'.
 */
export const formatDateToISODateString = (
  date: string | Date = '',
  timeZone = 'Asia/Ho_Chi_Minh',
): string => {
  const dt = DateTime.unsafeFromDate(new Date(date));
  const zoned = DateTime.unsafeMakeZoned(dt, { timeZone });
  const { year, month, day } = DateTime.toParts(zoned);
 
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
};
 
/**
 * Parse a date string with a given format
 * @param dateStr - The date string (e.g., "20250822")
 * @param formatStr - The format to parse (default: "yyyyMMdd")
 * @returns Date object
 */
export const parseDay = (dateStr: string, formatStr = 'yyyyMMdd') => {
  return parse(dateStr, formatStr, new Date());
};
 
/**
 * Formats a date string (`yyyyMMdd`) based on the selected chart mode.
 *
 * - Week & Month → "EEE dd" (e.g., "Fri 05")
 * - Quarter & Year → "MMM dd" (e.g., "Sep 05")
 *
 * @param dateString - Date in `yyyyMMdd` format (e.g., "20250905")
 * @param mode - Chart mode that determines the formatting style (default: Week)
 * @returns Formatted date string or an empty string if input is invalid
 */
export const formatDateByMode = (
  dateString?: string,
  mode: ChartMode = ChartMode.Week,
): string => {
  if (!dateString || dateString.length < 8) return '';
 
  const parsed = parse(dateString, 'yyyyMMdd', new Date());
  if (isNaN(parsed.getTime())) return '';
 
  const pattern = DATE_FORMATS[mode] ?? 'EEE dd';
  return format(parsed, pattern);
};
 
/**
 * Returns the current date/time in the given timezone.
 */
const getLocalNow = (timeZone = 'Asia/Ho_Chi_Minh') => {
  const utc = DateTime.unsafeNow();
  const jsDate = DateTime.toDate(utc);
 
  return toZonedTime(jsDate, timeZone);
};
 
/**
 * Check if a given date is after the cutoff time (e.g., 11:30 AM) in its day.
 */
const isAfterCutoff = (date: Date, hour = 11, minute = 30): boolean => {
  const cutoff = setMinutes(setHours(startOfDay(date), hour), minute);
  return isAfter(date, cutoff);
};
 
const TIME_RANGE_GENERATORS: Record<ChartMode, () => string> = {
  [ChartMode.Week]: () => {
    const lastWeekStart = startOfWeek(subWeeks(new Date(), 1), {
      weekStartsOn: 1,
    });
    return TIME_RANGE_FORMATTER.WEEK(lastWeekStart);
  },
  [ChartMode.Month]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the month → go back one more month
    const isFirstDayOfMonth = isSameDay(localNow, startOfMonth(localNow));
    const monthsBack = isFirstDayOfMonth && !isPastCutoff ? 2 : 1;
    const targetMonth = subMonths(localNow, monthsBack);
 
    return TIME_RANGE_FORMATTER.MONTH(targetMonth);
  },
  [ChartMode.Quarter]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the quarter → go back one more quarter
    const isFirstDayOfQuarter = isSameDay(localNow, startOfQuarter(localNow));
    const quartersBack = isFirstDayOfQuarter && !isPastCutoff ? 2 : 1;
    const lastQuarter = subQuarters(localNow, quartersBack);
    const year = TIME_RANGE_FORMATTER.YEAR(lastQuarter);
    const quarter = Math.floor(lastQuarter.getMonth() / 3) + 1;
 
    return `${year}Q${quarter}`;
  },
  [ChartMode.Year]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the year → go back one more year
    const isFirstDayOfYear = isSameDay(localNow, startOfYear(localNow));
    const yearsBack = isFirstDayOfYear && !isPastCutoff ? 2 : 1;
    const lastYear = subYears(localNow, yearsBack);
 
    return TIME_RANGE_FORMATTER.YEAR(lastYear);
  },
};
 
/**
 * Returns the default time range string for a given chart mode.
 *
 * @param mode - ChartMode (Week, Month, Quarter, Year)
 * @returns string representing the default time range
 */
export const getDefaultTimeRange = (mode: ChartMode): string => {
  return TIME_RANGE_GENERATORS[mode]?.() ?? '';
};
 
type periodRange = {
  weeks: { from: Date; to?: Date }[];
  months: { year: number; month: number }[];
  quarters: { year: number; quarter: number }[];
  years: number[];
};
 
/**
 * Format a given set of time ranges into a comma-separated string,
 * depending on the chart mode.
 *
 * @param mode - The chart mode (Week, Month, Quarter, Year).
 * @param timeRanges - An object containing arrays of period ranges
 *   for different modes (weeks, months, quarters, years).
 *
 * @returns A comma-separated string representing the time ranges
 *   formatted for the specified chart mode.
 *  "20250908" / "202501" / "2025Q1" / "2024,2023"
 */
export const formatTimeRanges = (
  mode: ChartMode,
  timeRanges: periodRange,
): string => {
  const FORMATTERS: Record<ChartMode, () => string> = {
    [ChartMode.Week]: () =>
      timeRanges.weeks.map((w) => TIME_RANGE_FORMATTER.WEEK(w.from)).join(','),
 
    [ChartMode.Month]: () =>
      timeRanges.months
        .map((m) => `${m.year}${String(m.month + 1).padStart(2, '0')}`)
        .join(','),
 
    [ChartMode.Quarter]: () =>
      timeRanges.quarters.map((q) => `${q.year}Q${q.quarter}`).join(','),
 
    [ChartMode.Year]: () => timeRanges.years.join(','),
  };
 
  return FORMATTERS[mode]();
};
 
/**
 * Convert a year-quarter string (e.g., "2025Q1") into an array of
 * three month identifiers in "yyyyMM" format.
 *
 * @param yearQuarter - A string in the format "YYYYQ#", where # is
 *   the quarter number (1–4).
 *
 * @returns An array of strings representing the months in that quarter,
 *   each in "yyyyMM" format. Returns an empty array if the input is invalid.
 *
 * @example
 * getQuarterDate("2025Q1");
 * => ["202501", "202502", "202503"]
 */
export const getQuarterDate = (yearQuarter: string) => {
  const match = yearQuarter.match(/^(\d{4})Q([1-4])$/);
  if (!match) return [];
  const year = Number(match[1]);
  const quarter = Number(match[2]);
 
  const startMonth = (quarter - 1) * 3 + 1;
  return Array.from({ length: 3 }, (_, i) => {
    const month = startMonth + i;
    return `${year}${month.toString().padStart(2, '0')}`;
  });
};
 
/**
 * Parse a comma-separated string of time ranges into an array of trimmed strings.
 *
 * @param timeRanges - A string containing time ranges separated by commas (e.g. "2024,2023").
 * @returns An array of non-empty, trimmed time range strings.
 *
 * @example
 * parseTimeRanges("2024, 2023"); // ["2024", "2023"]
 * parseTimeRanges("2024");       // ["2024"]
 * parseTimeRanges("");           // []
 */
export const parseTimeRanges = (timeRanges: string): string[] => {
  if (!timeRanges) return [];
  return timeRanges
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
};
 
/**
 * Check if voting for a meal is currently open.
 *
 * Voting is only allowed on the current day (`isToday`)
 * and only after the specified start time (default: 11:30 AM).
 *
 * @param date - The meal's date (string or Date).
 * @param startHour - Hour of day when voting opens (default: 11).
 * @param startMinute - Minute of hour when voting opens (default: 30).
 * @param timeZone - IANA time zone string (default: "Asia/Ho_Chi_Minh").
 * @returns True if voting is allowed, false otherwise.
 */
export const isVoteOpen = (
  date: string | Date,
  startHour = 11,
  startMinute = 30,
  timeZone = 'Asia/Ho_Chi_Minh',
): boolean => {
  const mealDate = typeof date === 'string' ? new Date(date) : date;
 
  // Get the "now" in the desired timezone
  const now = toZonedTime(new Date(), timeZone);
 
  // Compare only if the mealDate is today (in that timezone)
  const mealDateStr = mealDate.toISOString();
  if (!isToday(mealDateStr)) return false;
 
  const startTime = toZonedTime(mealDate, timeZone);
  startTime.setHours(startHour, startMinute, 0, 0);
 
  return now >= startTime;
};
 
/**
 * Check if the feedback window for a meal is currently open.
 *
 * The feedback window spans 24 hours: from 11:30 AM on the meal day
 * to 11:30 AM the following day.
 *
 * @param dateStr - The meal's date (ISO string).
 * @param startHour - Hour when the window opens (default: 11).
 * @param startMinute - Minute when the window opens (default: 30).
 * @param timeZone - IANA time zone string (default: "Asia/Ho_Chi_Minh").
 * @returns True if the current time falls within the feedback window.
 */
export const isFeedbackOpen = (
  dateStr: string,
  startHour = 11,
  startMinute = 30,
  timeZone = 'Asia/Ho_Chi_Minh',
): boolean => {
  // Today's meal after startHour:startMinute → window just opened
  if (isVoteOpen(dateStr, startHour, startMinute, timeZone)) return true;
  // Already past next-day cutoff → window closed
  if (isExpiredDay(dateStr, startHour, startMinute, timeZone)) return false;
  // Yesterday's meal, before today's cutoff → still within the 24h window
  const inputDate = toZonedTime(new Date(dateStr), timeZone);
  const now = toZonedTime(new Date(), timeZone);
  return differenceInCalendarDays(now, inputDate) === 1;
};
 
/**
 * Returns the current moment as a naive (no-Z, no-offset) local-time string in
 * the kitchen timezone. Passing this to `formatRelativeTime` avoids the
 * Z-reinterpretation that shifts server UTC timestamps by 7 hours.
 */
export const getNaiveLocalNow = (timeZone = KITCHEN_TIMEZONE): string => {
  const zoned = toZonedTime(new Date(), timeZone);
  return format(zoned, DATE_FORMAT.NAIVE_ISO_DATE_TIME);
};
 
/**
 * Format a week range (Monday–Friday) into a short string.
 * Ex: { from: "2025-11-03T00:00:00+07:00", to: "2025-11-07T00:00:00+07:00" }
 * → "03.11 - 07.11"
 *
 * @param range - Object with `from` and `to` date values (Date or string)
 * @returns Formatted string in "dd.MM - dd.MM" format
 */
export const getFormattedWeekRange = ({
  from,
  to,
}: {
  from: string | Date;
  to: string | Date;
}): string => {
  if (!from || !to) return '';
 
  const fromDate = new Date(from);
  const toDate = new Date(to);
 
  return `${format(fromDate, 'dd.MM')} - ${format(toDate, 'dd.MM')}`;
};
 
const ISO_DATE_TIME_WITH_Z =
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(\.\d{1,3})?Z$/i;
const ISO_DATE_TIME_NAIVE =
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(\.\d{1,3})?$/;
 
/**
 * Parses timestamps for relative-time display.
 *
 * - ISO strings ending in `Z` are treated as real UTC (via `new Date()`).
 * - Naive ISO strings (no offset) are treated as Vietnam local wall-clock time.
 */
const parseRelativeTimeDate = (
  date: string | Date | number | null | undefined,
): Date | null => {
  if (date == null) {
    return null;
  }
 
  if (date instanceof Date) {
    return Number.isNaN(date.getTime()) ? null : date;
  }
 
  if (typeof date === 'number') {
    const parsed = new Date(date);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
  }
 
  const trimmed = date.trim();
 
  if (!trimmed) {
    return null;
  }
 
  if (ISO_DATE_TIME_WITH_Z.test(trimmed)) {
    const parsed = new Date(trimmed);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
  }
 
  if (ISO_DATE_TIME_NAIVE.test(trimmed)) {
    const parsed = fromZonedTime(trimmed, KITCHEN_TIMEZONE);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
  }
 
  const parsed = new Date(trimmed);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
};
 
/**
 * Formats a date string into a relative time format.
 *
 * Example (Asia/Ho_Chi_Minh, now = 2026-06-17 09:46):
 * - "2026-06-17T08:00:00Z" -> "1 hour"
 * - "2026-06-16T08:00:00Z" -> "1 day"
 *
 * Returns an empty string when the input is missing or not a valid date.
 */
export const normalizeDateString = (
  date: string | Date | number | null | undefined,
): string => {
  if (date == null) {
    return '';
  }
 
  if (date instanceof Date) {
    return Number.isNaN(date.getTime()) ? '' : date.toISOString();
  }
 
  if (typeof date === 'number') {
    const parsed = new Date(date);
    return Number.isNaN(parsed.getTime()) ? '' : parsed.toISOString();
  }
 
  if (typeof date === 'string') {
    return date.trim();
  }
 
  return String(date).trim();
};
 
/**
 * Formats a date string into the comment group header format.
 * Example: "2026-06-24T00:00:00.000Z" → "Monday, Jun 24, 2026"
 *
 * @param dateStr - The ISO date string to format
 * @returns A formatted date string like "Monday, Jun 24, 2026"
 */
export const formatCommentGroupDate = (dateStr: string): string => {
  const date = new Date(dateStr);
  return format(date, DATE_FORMAT.COMMENT_GROUP_DATE);
};
 
/** Same as formatCommentGroupDate but without the year, e.g. "Monday, Jun 24". */
export const formatCommentGroupDateNoYear = (dateStr: string): string => {
  const date = new Date(dateStr);
  return format(date, DATE_FORMAT.COMMENT_GROUP_DATE_NO_YEAR);
};
 
/**
 * Formats a date string into the feedback header date format.
 * Example: "2026-07-10T00:00:00+07:00" -> "Fri, Jul 10, 2026"
 * Returns an empty string when the input is missing or not a valid date.
 */
export const formatFeedbackDate = (
  date: string | Date | number | null | undefined,
): string => {
  const parsed = parseRelativeTimeDate(date);
  if (!parsed) return '';
  return format(parsed, DATE_FORMAT.FEEDBACK_DATE);
};
 
/** Returns YYYYMMDD (no hyphens) — matches the comments API date param format. Returns '' for null/undefined/invalid input. */
export const toCompactDateString = (
  d: string | Date | undefined | null,
): string => (d ? formatDateToISODateString(d).replace(/-/g, '') : '');
 
/** Get the first day of the month for a given date (month start at midnight local time). */
export const getMonthStartDate = (date: Date): Date =>
  new Date(date.getFullYear(), date.getMonth(), 1);
 
/** Get the last day of the month for a given date (month end at midnight local time). */
export const getMonthEndDate = (date: Date): Date =>
  new Date(date.getFullYear(), date.getMonth() + 1, 0);
 
/** Get compact date strings (YYYYMMDD) for the visible month range. */
export const getMonthDateRange = (
  visibleMonth: Date,
): { fromDate: string; toDate: string } => ({
  fromDate: toCompactDateString(getMonthStartDate(visibleMonth)),
  toDate: toCompactDateString(getMonthEndDate(visibleMonth)),
});
 
export const formatAbsoluteTime = (
  date: string | Date | number | null | undefined,
): string => {
  const parsed = parseRelativeTimeDate(date);
  if (!parsed) return '';
  return format(parsed, DATE_FORMAT.ABSOLUTE_TIME);
};
 
/** Returns a compact date string like "Jun 24" for use alongside a time display. */
export const formatShortDate = (
  date: string | Date | number | null | undefined,
): string => {
  const parsed = parseRelativeTimeDate(date);
  if (!parsed) return '';
  return format(parsed, 'MMM d');
};
 
export const formatRelativeTime = (
  date: string | Date | number | null | undefined,
): string => {
  const parsed = parseRelativeTimeDate(date);
 
  if (!parsed) {
    return '';
  }
 
  const now = new Date();
  const diffInSeconds = Math.abs(differenceInSeconds(now, parsed));
 
  if (diffInSeconds < 60) {
    return 'Just now';
  }
 
  const diffInMinutes = Math.abs(differenceInMinutes(now, parsed));
 
  if (diffInMinutes >= 5 && diffInMinutes < 60) {
    const roundedMinutes = Math.floor(diffInMinutes / 5) * 5;
 
    return `${roundedMinutes} minutes`;
  }
 
  return formatDistanceStrict(parsed, now, {
    addSuffix: false,
    roundingMethod: 'floor',
  });
};
 
export const isDateRangeExceededMonths = (
  from: Date,
  to: Date,
  maxMonths: number,
): boolean => {
  const monthDiff =
    (to.getFullYear() - from.getFullYear()) * 12 +
    (to.getMonth() - from.getMonth());
 
  return Math.abs(monthDiff) > maxMonths;
};