부품 가게·기관 정보

운영 시간 business-hours

요일별 운영 시간 표. 같은 시간인 요일을 한 줄로 묶고 오늘 줄을 강조하며, 지금이 운영 중·휴게 시간·마감인지 방문자의 현재 시각으로 계산한다(화면이 뜬 뒤 계산, now 로 고정 가능). 야간 운영일과 휴무일을 따로 표시하고, 상태 한 줄만 쓰는 OpenStatus 도 함께 내보낸다.

  • 나온 곳 온유치과
  • 진료 시간
  • 영업시간
  • 오늘 운영
  • 점심시간
  • 야간 진료
  • 휴무

설치

shadcn/ui 를 쓰는 Next.js 프로젝트에서 한 줄로 설치됩니다. 파일은 components/bpublish/business-hours.tsx 로 들어오고, 공통 토큰(base)과 함께 쓰는 부품(section-head)도 같이 설치됩니다. 테마는 테마에서 하나 고릅니다.

npx shadcn@latest add https://www.bpublish.com/r/business-hours.json

레지스트리를 등록했다면 npx shadcn@latest add @bpublish/business-hours · 설치 안내

AI에게 맡기기

Claude Code, Cursor 같은 AI 코딩 도구에 붙여 넣으세요. MCP 서버를 연결해 두면 이름만 말해도 됩니다.

bpublish UI의 운영 시간(business-hours) 부품으로 만들어 줘. 설치: npx shadcn@latest add https://www.bpublish.com/r/business-hours.json · 문서: https://www.bpublish.com/designs/components/business-hours

사용 예시

app/page.tsx
import { BusinessHours, type DayHours } from '@/components/bpublish/business-hours'

const week: DayHours[] = [
  {},
  { open: '09:30', close: '18:30', breakTime: ['13:00', '14:00'] },
  { open: '09:30', close: '21:00', breakTime: ['13:00', '14:00'], night: true },
  { open: '09:30', close: '18:30', breakTime: ['13:00', '14:00'] },
  { open: '09:30', close: '21:00', breakTime: ['13:00', '14:00'], night: true },
  { open: '09:30', close: '18:30', breakTime: ['13:00', '14:00'] },
  { open: '09:30', close: '14:00', note: '점심시간 없이 진료' },
]

export default function Example() {
  return (
    <BusinessHours
      title="진료 시간"
      description="화요일과 목요일은 밤 9시까지 진료합니다. 퇴근 후에도 예약 없이 검진을 받으실 수 있습니다."
      week={week}
      term="진료"
      closedTerm="휴진"
      breakLabel="점심시간"
      nightLabel="야간 진료"
      holidayLabel="공휴일"
      notes={['야간 진료일의 마지막 접수는 20시 30분입니다.', '토요일은 예약하신 분을 먼저 진료합니다.', '임플란트 수술과 교정 상담은 예약제로 운영합니다.']}
      phone={{ label: '전화 예약', number: '031-000-0000' }}
    />
  )
}

속성

이름형식기본값설명
week필수{ open?: string; close?: string; breakTime?: [string, string]; night?: boolean; note?: string }[]—요일별 시간 7개. 0 = 일요일 … 6 = 토요일. open 이 없으면 휴무
titlestring—구역 제목
eyebrowstring—제목 위 영문 소제목
descriptionstring—제목 옆 설명
termstring'영업'상태 낱말. '진료' → 진료 중 · 진료 전 · 진료 마감
closedTermstring'휴무'쉬는 날 낱말. '휴진' → 오늘 휴진
breakLabelstring'휴게 시간'휴게 시간 이름 (점심시간 등)
nightLabelstring'야간'야간 운영일 표시
holidayLabelstring—쉬는 요일 줄 끝에 붙는 말 (예: '공휴일')
notesstring[]—표 아래 안내
phone{ label: string; number: string }—맨 아래 전화 줄
nowDate | string | number—지금 시각 고정 (미리보기·시험용). 없으면 방문자 기기의 현재 시각
timeZonestring'Asia/Seoul'상태를 계산하는 시간대
closedDatesstring[]—임시 휴무일 'YYYY-MM-DD'
weekStart0 | 11표를 시작하는 요일 (1 = 월요일)
dayNamesstring[]['일','월','화','수','목','금','토']요일 이름

원본 코드

설치 명령 없이 그대로 복사해 넣어도 됩니다. React 외의 패키지는 쓰지 않습니다.

components/bpublish/business-hours.tsx
'use client'

/**
 * bpublish UI — 운영 시간. https://www.bpublish.com/designs/components/business-hours
 * 요일별 운영 시간 표. 같은 시간인 요일을 한 줄로 묶고, 오늘 줄을 강조하고, 지금이 운영 중·휴게 시간·마감인지 현재 시각으로 계산한다.
 * 휴무일과 야간 운영일을 따로 표시한다. 상태 한 줄만 필요하면 OpenStatus 를 따로 쓴다(머리 위 정보 줄 등).
 */
import { useEffect, useState } from 'react'
import { SectionHead } from './section-head'

/** 하루 운영 시간. open 이 없으면 휴무일 */
export type DayHours = {
  /** 여는 시각 'HH:MM' */
  open?: string
  /** 닫는 시각 'HH:MM' */
  close?: string
  /** 점심·휴게 시간 ['13:00', '14:00'] */
  breakTime?: [string, string]
  /** 야간 운영일 (표와 요일 띠에 강조색으로 표시) */
  night?: boolean
  /** 그 줄 오른쪽에 붙는 짧은 말 */
  note?: string
}

export type HoursWords = {
  /** 상태 문장의 낱말. '진료' → 진료 중 · 진료 전 · 진료 마감 */
  term?: string
  /** 쉬는 날 낱말. '휴진' → 오늘 휴진 */
  closedTerm?: string
  /** 휴게 시간 이름 */
  breakLabel?: string
  /** 야간 운영 표시 */
  nightLabel?: string
  /** 요일 이름. 0 = 일요일 */
  dayNames?: string[]
}

type HoursBase = HoursWords & {
  /** 요일별 시간 7개. 0 = 일요일 … 6 = 토요일 (Date.getDay 순서) */
  week: DayHours[]
  /** 지금 시각을 고정한다(미리보기·시험용). 없으면 방문자 기기의 현재 시각 */
  now?: Date | string | number
  /** 상태를 계산할 시간대 */
  timeZone?: string
  /** 임시 휴무일 'YYYY-MM-DD' */
  closedDates?: string[]
}

export type OpenStatusProps = HoursBase & { className?: string }

export type BusinessHoursProps = HoursBase & {
  title?: string
  eyebrow?: string
  description?: string
  /** 쉬는 요일 줄 끝에 붙는 말 (예: '공휴일' → 일요일 · 공휴일) */
  holidayLabel?: string
  /** 표 아래 안내 몇 줄 */
  notes?: string[]
  /** 맨 아래 전화 줄 */
  phone?: { label: string; number: string }
  /** 표를 시작하는 요일. 1 = 월요일 */
  weekStart?: 0 | 1
  className?: string
}

/* ── 계산 ───────────────────────────────────────────────────────── */

const EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const DAY_NAMES = ['일', '월', '화', '수', '목', '금', '토']
const toMin = (t: string) => {
  const [h, m] = t.split(':').map(Number)
  return h * 60 + (m || 0)
}

function partsIn(date: Date, timeZone: string) {
  const f = new Intl.DateTimeFormat('en-US', {
    timeZone,
    weekday: 'short',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hourCycle: 'h23',
  })
  const p = Object.fromEntries(f.formatToParts(date).map((x) => [x.type, x.value]))
  return { dow: EN.indexOf(p.weekday), minutes: (Number(p.hour) % 24) * 60 + Number(p.minute), ymd: `${p.year}-${p.month}-${p.day}` }
}

type Status = { dow: number; kind: 'open' | 'break' | 'before' | 'after' | 'closed'; at?: string; next?: { offset: number; dow: number; time: string } }

function statusAt(date: Date, week: DayHours[], timeZone: string, closedDates: string[] = []): Status {
  const p = partsIn(date, timeZone)
  const isOpen = (dow: number, ymd: string) => Boolean(week[dow]?.open && week[dow]?.close) && !closedDates.includes(ymd)
  const findNext = () => {
    for (let i = 1; i <= 14; i++) {
      const q = partsIn(new Date(date.getTime() + i * 86400000), timeZone)
      if (isOpen(q.dow, q.ymd)) return { offset: i, dow: q.dow, time: week[q.dow].open! }
    }
    return undefined
  }
  if (!isOpen(p.dow, p.ymd)) return { dow: p.dow, kind: 'closed', next: findNext() }
  const d = week[p.dow]
  const open = toMin(d.open!)
  let close = toMin(d.close!)
  if (close <= open) close += 1440
  if (p.minutes < open) return { dow: p.dow, kind: 'before', at: d.open }
  if (d.breakTime && p.minutes >= toMin(d.breakTime[0]) && p.minutes < toMin(d.breakTime[1])) return { dow: p.dow, kind: 'break', at: d.breakTime[1] }
  if (p.minutes < close) return { dow: p.dow, kind: 'open', at: d.close }
  return { dow: p.dow, kind: 'after', next: findNext() }
}

/** 서버와 첫 화면에서는 null(고정 시각이 있으면 그 시각), 화면이 뜬 뒤 현재 시각. 30초마다 다시 잰다 */
function useNow(now?: Date | string | number) {
  const key = now instanceof Date ? now.getTime() : now
  const [t, setT] = useState<Date | null>(key != null ? new Date(key) : null)
  useEffect(() => {
    if (key != null) {
      setT(new Date(key))
      return
    }
    const tick = () => setT(new Date())
    tick()
    const id = setInterval(tick, 30000)
    return () => clearInterval(id)
  }, [key])
  return t
}

function words(w: HoursWords) {
  return {
    term: w.term ?? '영업',
    closedTerm: w.closedTerm ?? '휴무',
    breakLabel: w.breakLabel ?? '휴게 시간',
    nightLabel: w.nightLabel ?? '야간',
    dayNames: w.dayNames ?? DAY_NAMES,
  }
}

function describe(s: Status, w: ReturnType<typeof words>) {
  const next = s.next ? `${s.next.offset === 1 ? '내일' : `${w.dayNames[s.next.dow]}요일`} ${s.next.time}부터` : ''
  switch (s.kind) {
    case 'open':
      return { head: `${w.term} 중`, detail: `${s.at}까지`, live: true }
    case 'break':
      return { head: w.breakLabel, detail: `${s.at}부터`, live: false }
    case 'before':
      return { head: `${w.term} 전`, detail: `${s.at}부터`, live: false }
    case 'after':
      return { head: `${w.term} 마감`, detail: next, live: false }
    default:
      return { head: `오늘 ${w.closedTerm}`, detail: next, live: false }
  }
}

function Dot({ live }: { live: boolean }) {
  return <span aria-hidden className={`inline-block size-2 shrink-0 rounded-full ${live ? 'bg-primary' : 'bg-muted-foreground/45'}`} />
}

/* ── 상태 한 줄 ─────────────────────────────────────────────────── */

/** '● 진료 중 · 18:30까지' 한 줄. 화면이 뜬 뒤에 계산한다 */
export function OpenStatus({ week, now, timeZone = 'Asia/Seoul', closedDates, className = '', ...rest }: OpenStatusProps) {
  const t = useNow(now)
  const w = words(rest)
  if (!t) return <span className={`inline-block min-w-24 ${className}`}>&nbsp;</span>
  const d = describe(statusAt(t, week, timeZone, closedDates), w)
  return (
    <span className={`inline-flex min-w-0 items-center gap-2 tabular-nums ${className}`}>
      <Dot live={d.live} />
      <span className="font-medium text-foreground">{d.head}</span>
      {d.detail ? <span className="truncate">· {d.detail}</span> : null}
    </span>
  )
}

/* ── 운영 시간 구역 ─────────────────────────────────────────────── */

type Row = { key: string; days: number[]; time: string; note?: string; night?: boolean; closed?: boolean; isBreak?: boolean }

function joinDays(days: number[], names: string[]) {
  return days.length === 1 ? `${names[days[0]]}요일` : days.map((d) => names[d]).join(' · ')
}

function buildRows(week: DayHours[], order: number[], w: ReturnType<typeof words>): Row[] {
  const open: Row[] = []
  const closed: Row[] = []
  const breaks: Row[] = []
  for (const dow of order) {
    const d = week[dow] ?? {}
    if (!d.open || !d.close) {
      const r = closed[0]
      if (r) r.days.push(dow)
      else closed.push({ key: 'closed', days: [dow], time: w.closedTerm, closed: true })
      continue
    }
    const key = [d.open, d.close, d.night, d.note, d.breakTime?.join()].join('|')
    const r = open.find((x) => x.key === key)
    if (r) r.days.push(dow)
    else open.push({ key, days: [dow], time: `${d.open} – ${d.close}`, note: d.night ? w.nightLabel : d.note, night: d.night })
    if (d.breakTime) {
      const bk = `break|${d.breakTime.join()}`
      const b = breaks.find((x) => x.key === bk)
      if (b) b.days.push(dow)
      else breaks.push({ key: bk, days: [dow], time: `${d.breakTime[0]} – ${d.breakTime[1]}`, isBreak: true })
    }
  }
  const openDays = order.filter((d) => week[d]?.open)
  for (const b of breaks) {
    const weekdays = b.days.length === 5 && [1, 2, 3, 4, 5].every((d) => b.days.includes(d))
    b.note = weekdays ? '평일' : b.days.length === openDays.length ? undefined : b.days.map((d) => w.dayNames[d]).join(' · ')
  }
  return [...open, ...breaks, ...closed]
}

export function BusinessHours({
  week,
  now,
  timeZone = 'Asia/Seoul',
  closedDates,
  title,
  eyebrow,
  description,
  holidayLabel,
  notes = [],
  phone,
  weekStart = 1,
  className = '',
  ...rest
}: BusinessHoursProps) {
  const t = useNow(now)
  const w = words(rest)
  const order = weekStart === 1 ? [1, 2, 3, 4, 5, 6, 0] : [0, 1, 2, 3, 4, 5, 6]
  const rows = buildRows(week, order, w)
  const status = t ? statusAt(t, week, timeZone, closedDates) : null
  const today = status?.dow
  const d = status ? describe(status, w) : null

  return (
    <section className={`py-16 md:py-24 ${className}`}>
      <div className="shell">
        {title ? <SectionHead title={title} eyebrow={eyebrow} description={description} className="mb-12" /> : null}

        <div className="grid gap-x-10 gap-y-10 md:grid-cols-12">
          {/* 지금 상태 */}
          <div className="rounded-lg bg-muted px-6 py-6 md:col-span-5 md:col-start-8 md:px-7" aria-live="polite">
            <p className="text-[13px] text-muted-foreground">{status ? `오늘 ${w.dayNames[status.dow]}요일` : ' '}</p>
            <p className="heading mt-2 flex items-center gap-3 text-2xl md:text-[1.75rem]">
              {d ? (
                <>
                  <Dot live={d.live} />
                  {d.head}
                </>
              ) : (
                ' '
              )}
            </p>
            <p className="mt-1.5 text-[15px] text-muted-foreground tabular-nums">{d?.detail || ' '}</p>
          </div>

          {/* 요일별 표 */}
          <table className="w-full self-start text-left tabular-nums md:col-span-7 md:row-span-2 md:row-start-1">
            <caption className="sr-only">요일별 운영 시간</caption>
            <tbody>
              {rows.map((r) => {
                const isToday = today != null && !r.isBreak && r.days.includes(today)
                const label = r.isBreak ? w.breakLabel : r.closed && holidayLabel ? `${joinDays(r.days, w.dayNames)} · ${holidayLabel}` : joinDays(r.days, w.dayNames)
                return (
                  <tr key={r.key} className="border-b border-border first:border-t">
                    <th scope="row" className={`w-[42%] py-5 align-top text-[15px] leading-7 font-normal sm:w-[38%] md:text-base md:leading-8 ${isToday ? 'text-foreground' : 'text-muted-foreground'}`}>
                      <span className="flex flex-wrap items-center gap-x-2 gap-y-1">
                        {label}
                        {isToday ? <span className="rounded-full bg-primary px-2 py-px text-[11px] leading-[18px] font-semibold text-primary-foreground">오늘</span> : null}
                      </span>
                    </th>
                    <td
                      className={`py-5 align-top text-[19px] leading-7 whitespace-nowrap md:text-[22px] md:leading-8 ${
                        r.night ? 'font-medium text-primary' : r.closed || r.isBreak ? 'text-muted-foreground' : 'text-foreground'
                      }`}
                    >
                      {r.time}
                      {r.note ? <span className={`block text-[12.5px] leading-[1.6] sm:hidden ${r.night ? 'font-medium text-primary' : 'text-muted-foreground'}`}>{r.note}</span> : null}
                    </td>
                    <td className="hidden py-5 text-right align-top text-[13.5px] leading-7 text-muted-foreground sm:table-cell md:leading-8">
                      {r.night ? <span className="font-medium text-primary">{r.note}</span> : r.note}
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>

          {/* 요일 띠 · 안내 · 전화 */}
          <div className="md:col-span-5 md:col-start-8">
            <ol className="grid grid-cols-7 border border-border tabular-nums" aria-label="요일별 마치는 시각">
              {order.map((dow, i) => {
                const day = week[dow] ?? {}
                const on = Boolean(day.open && day.close)
                return (
                  <li
                    key={dow}
                    className={`flex flex-col items-center py-4 ${i > 0 ? 'border-l border-border' : ''} ${day.night ? 'bg-primary text-primary-foreground' : ''} ${
                      dow === today ? 'shadow-[inset_0_-3px_0_var(--foreground)]' : ''
                    }`}
                  >
                    <span className={`text-sm font-medium ${day.night ? '' : on ? 'text-foreground' : 'text-muted-foreground'}`}>{w.dayNames[dow]}</span>
                    <span className={`mt-2 text-[11.5px] sm:text-[12.5px] ${day.night ? '' : 'text-muted-foreground'}`}>{on ? day.close : w.closedTerm}</span>
                  </li>
                )
              })}
            </ol>

            {notes.length ? (
              <ul className="mt-8 space-y-3 text-[14.5px] leading-[1.7] text-muted-foreground">
                {notes.map((n) => (
                  <li key={n} className="flex gap-3">
                    <span aria-hidden className="mt-[11px] h-px w-3 shrink-0 bg-muted-foreground/60" />
                    {n}
                  </li>
                ))}
              </ul>
            ) : null}

            {phone ? (
              <a
                href={`tel:${phone.number.replace(/[^0-9+]/g, '')}`}
                className="mt-10 flex items-baseline justify-between gap-4 border-t border-foreground pt-5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
              >
                <span className="text-sm text-muted-foreground">{phone.label}</span>
                <span className="text-2xl font-medium tracking-[-0.01em] text-foreground tabular-nums">{phone.number}</span>
              </a>
            ) : null}
          </div>
        </div>
      </div>
    </section>
  )
}

함께 쓰는 부품