date.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /**
  2. * Date utilities for handling UTC timestamps from the backend.
  3. *
  4. * The backend stores all timestamps in UTC without timezone indicators.
  5. * These utilities ensure dates are properly interpreted as UTC and
  6. * displayed in the user's local timezone.
  7. */
  8. export type TimeFormat = 'system' | '12h' | '24h';
  9. export type DateFormat = 'system' | 'us' | 'eu' | 'iso';
  10. /**
  11. * Get the date input placeholder based on format setting.
  12. */
  13. export function getDatePlaceholder(dateFormat: DateFormat = 'system'): string {
  14. switch (dateFormat) {
  15. case 'us':
  16. return 'MM/DD/YYYY';
  17. case 'eu':
  18. return 'DD/MM/YYYY';
  19. case 'iso':
  20. return 'YYYY-MM-DD';
  21. case 'system':
  22. default: {
  23. // Try to detect system format
  24. const testDate = new Date(2000, 11, 31); // Dec 31, 2000
  25. const formatted = testDate.toLocaleDateString();
  26. if (formatted.startsWith('12')) return 'MM/DD/YYYY';
  27. if (formatted.startsWith('31')) return 'DD/MM/YYYY';
  28. return 'YYYY-MM-DD';
  29. }
  30. }
  31. }
  32. /**
  33. * Get the time input placeholder based on format setting.
  34. */
  35. export function getTimePlaceholder(timeFormat: TimeFormat = 'system'): string {
  36. switch (timeFormat) {
  37. case '12h':
  38. return 'HH:MM AM/PM';
  39. case '24h':
  40. return 'HH:MM';
  41. case 'system':
  42. default: {
  43. // Try to detect system format
  44. const testDate = new Date(2000, 0, 1, 14, 30);
  45. const formatted = testDate.toLocaleTimeString();
  46. if (formatted.includes('PM') || formatted.includes('AM')) return 'HH:MM AM/PM';
  47. return 'HH:MM';
  48. }
  49. }
  50. }
  51. /**
  52. * Format a Date object to a date string based on format setting.
  53. */
  54. export function formatDateInput(date: Date, dateFormat: DateFormat = 'system'): string {
  55. const day = String(date.getDate()).padStart(2, '0');
  56. const month = String(date.getMonth() + 1).padStart(2, '0');
  57. const year = date.getFullYear();
  58. switch (dateFormat) {
  59. case 'us':
  60. return `${month}/${day}/${year}`;
  61. case 'eu':
  62. return `${day}/${month}/${year}`;
  63. case 'iso':
  64. return `${year}-${month}-${day}`;
  65. case 'system':
  66. default:
  67. return date.toLocaleDateString();
  68. }
  69. }
  70. /**
  71. * Format a Date object to a time string based on format setting.
  72. */
  73. export function formatTimeInput(date: Date, timeFormat: TimeFormat = 'system'): string {
  74. const hours24 = date.getHours();
  75. const minutes = String(date.getMinutes()).padStart(2, '0');
  76. switch (timeFormat) {
  77. case '12h': {
  78. const hours12 = hours24 % 12 || 12;
  79. const ampm = hours24 < 12 ? 'AM' : 'PM';
  80. return `${hours12}:${minutes} ${ampm}`;
  81. }
  82. case '24h':
  83. return `${String(hours24).padStart(2, '0')}:${minutes}`;
  84. case 'system':
  85. default:
  86. return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  87. }
  88. }
  89. /**
  90. * Parse a date string based on format setting.
  91. * Returns null if parsing fails.
  92. */
  93. export function parseDateInput(value: string, dateFormat: DateFormat = 'system'): Date | null {
  94. if (!value) return null;
  95. let day: number, month: number, year: number;
  96. try {
  97. switch (dateFormat) {
  98. case 'us': {
  99. // MM/DD/YYYY
  100. const parts = value.split('/');
  101. if (parts.length !== 3) return null;
  102. month = parseInt(parts[0], 10);
  103. day = parseInt(parts[1], 10);
  104. year = parseInt(parts[2], 10);
  105. break;
  106. }
  107. case 'eu': {
  108. // DD/MM/YYYY
  109. const parts = value.split('/');
  110. if (parts.length !== 3) return null;
  111. day = parseInt(parts[0], 10);
  112. month = parseInt(parts[1], 10);
  113. year = parseInt(parts[2], 10);
  114. break;
  115. }
  116. case 'iso': {
  117. // YYYY-MM-DD
  118. const parts = value.split('-');
  119. if (parts.length !== 3) return null;
  120. year = parseInt(parts[0], 10);
  121. month = parseInt(parts[1], 10);
  122. day = parseInt(parts[2], 10);
  123. break;
  124. }
  125. case 'system':
  126. default: {
  127. // Try common formats
  128. const date = new Date(value);
  129. if (!isNaN(date.getTime())) return date;
  130. // Try EU format
  131. const euParts = value.split('/');
  132. if (euParts.length === 3) {
  133. day = parseInt(euParts[0], 10);
  134. month = parseInt(euParts[1], 10);
  135. year = parseInt(euParts[2], 10);
  136. break;
  137. }
  138. return null;
  139. }
  140. }
  141. if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
  142. if (month < 1 || month > 12) return null;
  143. if (day < 1 || day > 31) return null;
  144. if (year < 1900 || year > 2100) return null;
  145. return new Date(year, month - 1, day);
  146. } catch {
  147. return null;
  148. }
  149. }
  150. /**
  151. * Parse a time string. Handles both 12h (with AM/PM) and 24h formats.
  152. * Returns { hours, minutes } or null if parsing fails.
  153. */
  154. export function parseTimeInput(value: string): { hours: number; minutes: number } | null {
  155. if (!value) return null;
  156. try {
  157. const trimmed = value.trim().toUpperCase();
  158. // Check for 12h format with AM/PM
  159. const ampmMatch = trimmed.match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);
  160. if (ampmMatch) {
  161. let hours = parseInt(ampmMatch[1], 10);
  162. const minutes = parseInt(ampmMatch[2], 10);
  163. const ampm = ampmMatch[3]?.toUpperCase();
  164. if (ampm === 'PM' && hours < 12) hours += 12;
  165. if (ampm === 'AM' && hours === 12) hours = 0;
  166. if (hours < 0 || hours > 23) return null;
  167. if (minutes < 0 || minutes > 59) return null;
  168. return { hours, minutes };
  169. }
  170. // Try 24h format HH:MM
  171. const match24 = trimmed.match(/^(\d{1,2}):(\d{2})$/);
  172. if (match24) {
  173. const hours = parseInt(match24[1], 10);
  174. const minutes = parseInt(match24[2], 10);
  175. if (hours < 0 || hours > 23) return null;
  176. if (minutes < 0 || minutes > 59) return null;
  177. return { hours, minutes };
  178. }
  179. return null;
  180. } catch {
  181. return null;
  182. }
  183. }
  184. /**
  185. * Convert a Date object to datetime-local input value (ISO format).
  186. */
  187. export function toDateTimeLocalValue(date: Date): string {
  188. const year = date.getFullYear();
  189. const month = String(date.getMonth() + 1).padStart(2, '0');
  190. const day = String(date.getDate()).padStart(2, '0');
  191. const hours = String(date.getHours()).padStart(2, '0');
  192. const minutes = String(date.getMinutes()).padStart(2, '0');
  193. return `${year}-${month}-${day}T${hours}:${minutes}`;
  194. }
  195. /**
  196. * Apply time format setting to Intl.DateTimeFormatOptions.
  197. * This modifies the options object in place and returns it.
  198. */
  199. export function applyTimeFormat(
  200. options: Intl.DateTimeFormatOptions,
  201. timeFormat: TimeFormat = 'system'
  202. ): Intl.DateTimeFormatOptions {
  203. if (timeFormat === '12h') {
  204. options.hour12 = true;
  205. } else if (timeFormat === '24h') {
  206. options.hour12 = false;
  207. }
  208. // 'system' leaves hour12 undefined, letting the browser decide
  209. return options;
  210. }
  211. /**
  212. * Parse a date string from the backend as UTC.
  213. * Handles ISO 8601 strings with or without timezone indicators.
  214. *
  215. * @param dateStr - Date string from backend (e.g., "2026-01-09T12:03:36.288768")
  216. * @returns Date object in local timezone
  217. */
  218. export function parseUTCDate(dateStr: string | null | undefined): Date | null {
  219. if (!dateStr) return null;
  220. // If the string already has a timezone indicator, parse as-is
  221. if (dateStr.endsWith('Z') || /[+-]\d{2}:\d{2}$/.test(dateStr)) {
  222. return new Date(dateStr);
  223. }
  224. // Otherwise, append 'Z' to interpret as UTC
  225. return new Date(dateStr + 'Z');
  226. }
  227. /**
  228. * Format a UTC date string to a localized date/time string.
  229. *
  230. * @param dateStr - Date string from backend
  231. * @param options - Intl.DateTimeFormat options (defaults to showing date and time)
  232. * @returns Formatted date string in user's locale and timezone
  233. */
  234. export function formatDate(
  235. dateStr: string | null | undefined,
  236. options?: Intl.DateTimeFormatOptions
  237. ): string {
  238. const date = parseUTCDate(dateStr);
  239. if (!date) return '';
  240. const defaultOptions: Intl.DateTimeFormatOptions = {
  241. year: 'numeric',
  242. month: 'short',
  243. day: 'numeric',
  244. hour: '2-digit',
  245. minute: '2-digit',
  246. };
  247. return date.toLocaleString(undefined, options ?? defaultOptions);
  248. }
  249. /**
  250. * Format a UTC date string to a localized date-only string.
  251. *
  252. * @param dateStr - Date string from backend
  253. * @param options - Intl.DateTimeFormat options
  254. * @returns Formatted date string in user's locale and timezone
  255. */
  256. export function formatDateOnly(
  257. dateStr: string | null | undefined,
  258. options?: Intl.DateTimeFormatOptions
  259. ): string {
  260. const date = parseUTCDate(dateStr);
  261. if (!date) return '';
  262. const defaultOptions: Intl.DateTimeFormatOptions = {
  263. year: 'numeric',
  264. month: 'short',
  265. day: 'numeric',
  266. };
  267. return date.toLocaleDateString(undefined, options ?? defaultOptions);
  268. }
  269. /**
  270. * Format a UTC date string to a localized date/time string with time format support.
  271. *
  272. * @param dateStr - Date string from backend
  273. * @param timeFormat - Time format setting ('system', '12h', '24h')
  274. * @param options - Intl.DateTimeFormat options (defaults to showing date and time)
  275. * @returns Formatted date string in user's locale and timezone
  276. */
  277. export function formatDateTime(
  278. dateStr: string | null | undefined,
  279. timeFormat: TimeFormat = 'system',
  280. options?: Intl.DateTimeFormatOptions
  281. ): string {
  282. const date = parseUTCDate(dateStr);
  283. if (!date) return '';
  284. const defaultOptions: Intl.DateTimeFormatOptions = {
  285. year: 'numeric',
  286. month: 'short',
  287. day: 'numeric',
  288. hour: '2-digit',
  289. minute: '2-digit',
  290. };
  291. const finalOptions = applyTimeFormat(options ?? defaultOptions, timeFormat);
  292. return date.toLocaleString(undefined, finalOptions);
  293. }
  294. /**
  295. * Format a Date object to a localized time string with time format support.
  296. *
  297. * @param date - Date object
  298. * @param timeFormat - Time format setting ('system', '12h', '24h')
  299. * @param options - Additional Intl.DateTimeFormat options
  300. * @returns Formatted time string
  301. */
  302. export function formatTimeOnly(
  303. date: Date,
  304. timeFormat: TimeFormat = 'system',
  305. options?: Intl.DateTimeFormatOptions
  306. ): string {
  307. const defaultOptions: Intl.DateTimeFormatOptions = {
  308. hour: '2-digit',
  309. minute: '2-digit',
  310. };
  311. const finalOptions = applyTimeFormat({ ...defaultOptions, ...options }, timeFormat);
  312. return date.toLocaleTimeString([], finalOptions);
  313. }