summaryrefslogtreecommitdiff
path: root/lib/utils.ts
blob: af9df0576272030b216f515c10de50ea86471f75 (plain)
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
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export function formatDate(
  date: Date | string | number,
  locale: string = "en-US",
  opts: Intl.DateTimeFormatOptions = {},
  includeTime: boolean = false
) {
  return new Intl.DateTimeFormat(locale, {
    month: opts.month ?? "long",
    day: opts.day ?? "numeric",
    year: opts.year ?? "numeric",
    // Add time options when includeTime is true
    ...(includeTime && {
      hour: opts.hour ?? "2-digit",
      minute: opts.minute ?? "2-digit",
      second: opts.second ?? "2-digit",
      hour12: opts.hour12 ?? false, // Use 24-hour format by default
    }),
    ...opts, // This allows overriding any of the above defaults
  }).format(new Date(date))
}

// Alternative: Create a separate function for date and time
export function formatDateTime(
  date: Date | string | number| null | undefined,
  locale: string = "en-US",
  opts: Intl.DateTimeFormatOptions = {}
) {

  if (date === null || date === undefined || date === '') {
    return ''; // 또는 '-', 'N/A' 등 원하는 기본값 반환
  }

  return new Intl.DateTimeFormat(locale, {
    month: opts.month ?? "long",
    day: opts.day ?? "numeric",
    year: opts.year ?? "numeric",
    hour: opts.hour ?? "2-digit",
    minute: opts.minute ?? "2-digit",
    second: opts.second ?? "2-digit",
    hour12: opts.hour12 ?? false,
    ...opts,
  }).format(new Date(date))
}

export function toSentenceCase(str: string) {
  return str
    .replace(/_/g, " ")
    .replace(/([A-Z])/g, " $1")
    .toLowerCase()
    .replace(/^\w/, (c) => c.toUpperCase())
    .replace(/\s+/g, " ")
    .trim()
}

/**
 * @see https://github.com/radix-ui/primitives/blob/main/packages/core/primitive/src/primitive.tsx
 */
export function composeEventHandlers<E>(
  originalEventHandler?: (event: E) => void,
  ourEventHandler?: (event: E) => void,
  { checkForDefaultPrevented = true } = {}
) {
  return function handleEvent(event: E) {
    originalEventHandler?.(event)

    if (
      checkForDefaultPrevented === false ||
      !(event as unknown as Event).defaultPrevented
    ) {
      return ourEventHandler?.(event)
    }
  }
}