Search code examples
javascriptfullcalendar

How to show only opening hours in fullCalendar?


I'm using jQuery fullCalendar. A client wants to see only their bussiness opening hours in the calendar. Is that possible? How?

Example: a bussiness opens from 9am to 1pm and from 3pm to 10pm


Solution

  • On current fullcallendar version (5.x), maxTime and minTime options where renamed to slotMaxTime and slotMinTime.

    To hide most business time - i.e., night and/or non-working days:

    1. Calculate some values right from your businessHours specification
    const workSpec = [
      {
        daysOfWeek: [1, 2, 3, 4],
        startTime: '08:00',
        endTime: '18:00'
      }
      {
        daysOfWeek: [5],
        startTime: '09:00',
        endTime: '14:00'
      }
    ]
    
    /*
     * calculate the following:
     * - minimum "opening time"
     * - maximum "opening time"
     * - working days
     * - non-working days
     */
    const workMin = workSpec.map(item => item.startTime).sort().shift()
    const workMax = workSpec.map(item => item.endTime).sort().pop()
    const workDays = [...new Set(workSpec.flatMap(item => item.daysOfWeek))]
    const hideDays = [...Array(7).keys()].filter(day => !workDays.includes(day))
    
    1. Use calculated values on the related properties - i.e. for @fullcalendar/react:
    <FullCalendar
      //...
      businessHours={workSpec}
      slotMinTime={workMin}
      slotMaxTime={workMax}
      hiddenDays={hideDays}
      //...
    />
    

    Disclaimer: this was a quick-n-dirty go. There may be refactors to improve performance