use-format-date.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. 'use client'
  2. import { useDateSettings } from '@/components/date-settings-context'
  3. import {
  4. formatDate as fmtDate,
  5. formatDateTime as fmtDateTime,
  6. formatDayKey,
  7. formatTime as fmtTime,
  8. } from '@/lib/format'
  9. export function useFormatDate() {
  10. const { dateFormat, timeFormat, timezone } = useDateSettings()
  11. const tz = timezone || undefined
  12. return {
  13. formatDate: (date: Date | string) => fmtDate(date, dateFormat, tz),
  14. formatDateTime: (date: Date | string) => fmtDateTime(date, dateFormat, timeFormat, tz),
  15. formatTime: (date: Date | string) => fmtTime(date, timeFormat, tz),
  16. /**
  17. * A calendar day that is already a day, not an instant: a "YYYY-MM-DD"
  18. * key, or a date picker's local midnight. Written in the workshop's date
  19. * format without moving it through any zone. Any other string is an
  20. * instant, and is read on the workshop's clock like `formatDate`.
  21. */
  22. formatDay: (day: Date | string) =>
  23. typeof day !== 'string'
  24. ? fmtDate(day, dateFormat)
  25. : /^\d{4}-\d{2}-\d{2}$/.test(day)
  26. ? formatDayKey(day, dateFormat)
  27. : fmtDate(day, dateFormat, tz),
  28. }
  29. }