Usage | opening-hours-go | Spatie       

 SPATIE  

opening-hours-go
================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Opening-hours-go](https://spatie.be/docs/opening-hours-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/opening-hours-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/opening-hours-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/opening-hours-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/opening-hours-go/v1/usage)
- [ Testing ](https://spatie.be/docs/opening-hours-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/opening-hours-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/opening-hours-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/opening-hours-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Creating opening hours ](#content-creating-opening-hours)
2. [ Querying the schedule ](#content-querying-the-schedule)
3. [ Structured data ](#content-structured-data)
4. [ Value objects ](#content-value-objects)
5. [ Differences from PHP ](#content-differences-from-php)

The package is used through `OpeningHours`. Value types describe a `Time`, a `TimeRange`, a `Day` containing non-overlapping ranges, and a dated `DateTimeRange`.

Examples use these imports:

```
import (
    "encoding/json"
    "fmt"
    "time"

    openinghours "github.com/spatie/opening-hours-go"
)
```

Creating opening hours
--------------------------------------------------------------------------------------------------------------------------

`ParseJSON` fills a set of opening hours from a JSON definition. Not all days are mandatory. A missing day is closed.

```
hours, err := openinghours.ParseJSON([]byte(`{
    "monday": ["09:00-12:00", "13:00-18:00"],
    "exceptions": {
        "2016-12-25": [],
        "01-01": [],
        "12-25": ["09:00-12:00"]
    }
}`))
if err != nil {
    panic(err)
}
```

`New` takes a typed `Config`. `ParseDay` parses daily hours, and the zero `Day` is closed all day:

```
monday, err := openinghours.ParseDay("09:00-12:00", "13:00-18:00")
if err != nil {
    panic(err)
}
hours, err := openinghours.New(openinghours.Config{
    Week: map[string]openinghours.Day{"monday": monday},
    Exceptions: map[string]openinghours.Day{"12-25": {}},
})
if err != nil {
    panic(err)
}
```

Invalid inputs return errors. Use `errors.Is` with `ErrInvalidTime`, `ErrInvalidRange`, `ErrInvalidDay`, `ErrInvalidDate`, `ErrInvalidDefinition`, `ErrOverlap` or `ErrInvalidSpecification`. An empty object or empty array creates an always-closed schedule.

### Timezones

If no timezone is specified, opening hours assumes you pass dates in the timezone matching your schedule. A `time.Time` carrying an IANA `Location` retains its DST rules across searches.

If you specify a business timezone, passed dates are converted to it before querying. Returned dates are converted back to the input's location. Alternatively, specify both input and output timezone:

```
hours, err := openinghours.ParseJSON([]byte(`{
    "monday": ["09:00-12:00", "13:00-18:00"],
    "timezone": {"input": "America/New_York", "output": "Europe/Oslo"}
}`))
if err != nil {
    panic(err)
}
```

The `timezone` property also accepts a single IANA name or a fixed offset such as `-05:00`. With typed configuration, use `Config.Timezone` and `Config.OutputTimezone`, both `*time.Location`. Nil means no conversion.

Schedule wall times use `time.Date`, not elapsed hours after midnight. On spring and autumn DST transitions, elapsed opening time can differ from the wall-clock span. For a wall time inside a skipped or repeated hour, Go's `time.Date` selects an offset. It does not promise which of the two offsets it chooses. This is a difference from PHP's date normalization and Rust's fallible wall-time resolution.

### Merging overlapping ranges

For safety's sake, creating a day with overlapping ranges returns `ErrOverlap`. Explicitly merge them when needed:

```
hours, err := openinghours.ParseJSONAndMerge([]byte(`{
    "monday": ["08:00-11:00", "10:00-12:00"]
}`), true)
if err != nil {
    panic(err)
}
// Monday becomes 08:00-12:00.
```

`MergeRanges(ranges, ignoreData)` merges a typed slice without changing the input. Touching ranges merge too. With `ignoreData = false`, only ranges with deeply equal metadata merge. Different metadata can leave overlaps that `NewDay` still rejects. When metadata is ignored, the last merged range's data wins.

### Overnight hours

On construction, set a flag for overflowing times across days. For example, a nightclub opens until 3am on Friday and Saturday:

```
hours, err := openinghours.ParseJSON([]byte(`{
    "overflow": true,
    "friday": ["20:00-03:00"],
    "saturday": ["20:00-03:00"]
}`))
if err != nil {
    panic(err)
}
```

This allows `IsOpenAt` to look at the previous day's data. In typed configuration, use `Config.Overflow`.

You can also split a night into `22:00-24:00` followed by `00:00-07:00` on the next day. A range ending at `24:00` closes at midnight on the following date.

### Data

You can add data in definitions then retrieve them. JSON metadata can be strings, numbers, objects or arrays:

```
hours, err := openinghours.ParseJSON([]byte(`{
    "monday": {
        "hours": ["09:00-12:00", "13:00-18:00"],
        "data": "Typical Monday"
    },
    "tuesday": [
        "09:00-12:00",
        {"hours": "19:00-21:00", "data": "Extra on Tuesday evening"}
    ],
    "exceptions": {"2016-12-25": {"hours": [], "data": "Closed for Christmas"}}
}`))
if err != nil {
    panic(err)
}
monday, err := hours.ForDay(time.Monday)
if err != nil {
    panic(err)
}
fmt.Println(monday.Data()) // Typical Monday
```

Use `Config.Data`, `Day.WithData`, `TimeRange.WithData` or `Time.WithData` to attach any Go value, including application structs. `Data()` returns it. `NewDay` accepts typed ranges with their metadata. JSON range definitions also accept `["09:00-12:00", "metadata"]` pairs.

### Day and date ranges

You can use the separator `to` to specify multiple days at once, for the week or for exceptions:

```
hours, err := openinghours.ParseJSON([]byte(`{
    "monday to friday": ["09:00-19:00"],
    "saturday to sunday": [],
    "exceptions": {
        "12-24 to 12-26": {"hours": [], "data": "Holidays"},
        "2024-06-25 to 2024-07-01": {"hours": [], "data": "Closed for works"}
    }
}`))
if err != nil {
    panic(err)
}
```

Dash-separated forms such as `monday - wednesday`, `11-30-12-01` and `2024-06-25-2024-07-01` also work. Weekday ranges can wrap over Sunday. Date ranges are inclusive and cannot be reversed. Split recurring year-end holidays into two ranges. Recurring dates use a leap year for validation, so `02-29` is valid. Invalid dates, duplicate expanded days and overlapping date definitions return errors.

### Filters

A filter takes a date and returns settings for that date. The first filter returning true has precedence over later filters and all exceptions. Returning false means it does not apply. Returning `Day{}, true` closes the entire day.

```
hours, err := openinghours.ParseJSON([]byte(`{"monday": ["09:00-12:00"]}`),
    func(config *openinghours.Config) {
        config.Filters = []openinghours.DateFilter{
            func(date time.Time) (openinghours.Day, bool) {
                if date.Month() == time.December && date.Day() == 25 {
                    return openinghours.Day{}.WithData("Christmas"), true
                }
                return openinghours.Day{}, false
            },
        }
    },
)
if err != nil {
    panic(err)
}
```

`New(Config)` accepts the same callbacks through `Config.Filters`. `Filters()` returns a copy of the installed slice. Filters run for every date lookup and are not cached. Too many filters or slow work inside them can have a significant performance cost.

`ParseJSON`, `ParseJSONAndMerge` and `ParseStructuredData` accept optional `func(*Config)` callbacks. They run in order after parsing and before validation. Use them for custom filters, business and output locations, day limits, clocks and application metadata. Executable filters and PHP class names are not JSON options.

Schedules have no mutable setters. Keep configuration in your application and call `New` again when it changes. Metadata is not deep-copied. Treat shared metadata as immutable or synchronize it yourself. Concurrent queries are safe when your filters, clock and metadata are safe for concurrent use.

Querying the schedule
-----------------------------------------------------------------------------------------------------------------------

### For a week, day or date

`ForWeek()` returns a map from `time.Weekday` to `Day` for the regular schedule. `ForWeekCombined()` groups all days with the same hours. `ForWeekConsecutiveDays()` groups adjacent days with the same hours, from Monday to Sunday without looping. Both return ordered `[]WeekGroup` values. Metadata does not affect grouping.

`ForDay(time.Monday)` returns regular hours and an error if the weekday is invalid. `ForDate(date)` looks for filters, then a full-date exception, then a recurring month/day exception, and otherwise returns the regular schedule. `Exceptions()` returns a copy of all expanded exception keys and their days.

`IsOpenOn("saturday")` checks whether a regular day has at least one range. `IsOpenOn("2020-09-03")` checks the specific date, including exceptions and filters. `IsOpenOn("09-03")` uses the current year. `IsClosedOn` is its inverse. Both return `(bool, error)`.

### At a specific time

`IsOpenAt(date)` checks a specific instant, retaining seconds and nanoseconds. Opening times are inclusive, closing times exclusive. `IsClosedAt` is its inverse. `IsOpen()` and `IsClosed()` check right now. Set `Config.Now` to a `func() time.Time` to replace the clock for these methods and month/day queries.

`IsAlwaysOpen()` checks whether every regular and exceptional day is exactly `00:00-24:00`, with no filters. `IsAlwaysClosed()` checks whether they are all empty, with no filters. If an empty schedule is invalid in your domain, use this method to report an error.

`RegularClosingDays()` returns typed weekdays in Monday-to-Sunday order. `RegularClosingDaysISO()` returns their ISO numbers, with Monday = 1 and Sunday = 7. `ExceptionalClosingDates()` returns sorted closed exception keys, including recurring dates.

### Next and previous openings and closings

Returns the next open or close date/time from a given date/time:

```
date := time.Date(2016, 12, 24, 11, 0, 0, 0, time.UTC)
next, err := hours.NextOpen(date)
if err != nil {
    panic(err)
}
fmt.Println(next.Format("2006-01-02 15:04"))
```

`NextOpen` skips the current range's opening. `NextClose` includes its end. `PreviousOpen` and `PreviousClose` search backwards. Boundaries are strict, except that PHP-compatible midnight transitions can equal the input. Pass `time.Now()` to search from now.

The default search horizon is 8 days, or 366 when exceptions are present. Set `Config.DayLimit` to change it. Zero selects the default. Negative values are invalid. If no boundary is found, methods return `ErrMaximumLimit`. Always-open and always-closed schedules have no state change, so searches reach this limit.

All four methods accept an optional `SearchOptions`. `SearchUntil` returns `ErrSearchLimit` if a candidate passes the limit. `Cap` returns the cap instead. Both are absolute instants and apply to same-day candidates too. The cap is checked first. A zero time means no limit.

```
cap := date.Add(30 * time.Minute)
next, err := hours.NextOpen(date, openinghours.SearchOptions{Cap: cap})
if err != nil {
    panic(err)
}
```

### Open and closed time differences

`OpenDuration(start, end)` returns signed elapsed open time as `time.Duration`. `ClosedDuration` returns elapsed closed time. Reversing the arguments reverses the sign. Use `.Hours()`, `.Minutes()` or `.Seconds()` for the floating-point values provided by PHP's six `diffIn*` methods.

```
start := time.Date(2016, 12, 24, 11, 0, 0, 0, time.UTC)
end := time.Date(2016, 12, 24, 16, 34, 25, 0, time.UTC)
open, err := hours.OpenDuration(start, end)
if err != nil {
    panic(err)
}
fmt.Println(open.Hours())
```

Duration searches use the configured day limit too. Go durations can represent about 290 years. Keep the input span and accumulated duration within that limit.

### Current open range

`CurrentOpenRange(date)` returns `(DateTimeRange, true)` if there is a matching range, or false when there is none. `Start` and `End` are `time.Time` values with calendar dates and the configured output location. `CurrentOpenRangeStart` and `CurrentOpenRangeEnd` return the endpoints directly with a boolean.

The opening date can be yesterday for an overnight range. The closing date can be tomorrow. A `24:00` endpoint is midnight on the following date. Like PHP, range lookup considers the previous night even when `Overflow` is false. `IsOpenAt` only considers the previous night when the flag is true. If several ranges match across days, the previous night's last matching range wins.

`ForDateTime(date)` returns matching wall-time ranges, including those from the previous night.

### Collection callbacks

Use Go loops and slices rather than PHP's collection callback methods:

```
for weekday, day := range hours.ForWeek() {
    if day.IsEmpty() {
        fmt.Println(weekday)
    }
}
```

Maps have no iteration order. Use `ForWeekCombined` or `ForWeekConsecutiveDays` for ordered presentation. `Day.Ranges()` returns a copy in opening-time order.

Structured data
-----------------------------------------------------------------------------------------------------

`ParseStructuredData` fills the set from a schema.org `OpeningHoursSpecification` JSON array. `dayOfWeek` supports a single name, an array of names, or schema.org URLs:

```
hours, err := openinghours.ParseStructuredData([]byte(`[
    {
        "@type": "OpeningHoursSpecification",
        "opens": "08:00", "closes": "12:00",
        "dayOfWeek": ["https://schema.org/Monday", "Tuesday"]
    },
    {
        "@type": "OpeningHoursSpecification",
        "opens": "00:00", "closes": "00:00",
        "validFrom": "2023-12-25", "validThrough": "2023-12-25"
    }
]`))
if err != nil {
    panic(err)
}
data, err := json.Marshal(hours.AsStructuredData())
if err != nil {
    panic(err)
}
fmt.Println(string(data))
```

Structured data enables overnight ranges by default. `00:00-00:00` means closed all day. `23:59` as a closing time means the end of the day. Seconds in structured input are stripped. Missing opens and closes can both be null. `PublicHolidays` is unsupported.

`AsStructuredData()` returns `[]Specification`, ready for `json.Marshal`. It exports regular ranges followed by exceptions in sorted date order. Closed exception days use `00:00-00:00`. Metadata and executable filters are not exported.

`AsStructuredDataFormatted("15:04:05Z07:00", location)` customizes Go time formatting and offsets. The timezone is applied on 1970-01-01, just like PHP. It does not represent summer daylight-saving time.

Value objects
-----------------------------------------------------------------------------------------------

### Day

`Day` replaces PHP's `OpeningHoursForDay`. It is read-only. `ParseDay` parses strings and `NewDay` validates typed ranges. `Ranges()` returns a copy, `Len()` counts ranges and `IsEmpty()` checks for a closed day. `String()` joins ranges with commas.

`IsOpenAt`, `IsOpenAtNight`, `ForTime` and `ForNightTime` query the opening-day and next-morning portions. Day-level `NextOpen`, `NextClose`, `PreviousOpen` and `PreviousClose` return `(Time, bool)` and do not search other dates. Iterate over `Ranges()` when you need a range rather than a boundary.

### TimeRange

`ParseRange("09:00-12:00")` describes a period with a start and end. `Start()`, `End()`, `Data()`, `WithData()`, `String()` and `Format(layout, separator, location)` expose its values. `OverflowsNextDay()` checks whether the end precedes the start. `Contains` checks the opening-day portion and `ContainsNight` checks the following morning.

Unlike PHP's directional endpoint check, `Overlaps` is symmetric and excludes touching endpoints. Surrounding ranges are detected in either direction. Validation compares overnight intervals on their opening date. Ranges on different days may overlap when overflow is enabled.

### Time

`ParseTime("09:00")` accepts exactly `HH:MM`, including `24:00` but not `24:01`. `ParsePreciseTime` accepts seconds and fractional seconds. `TimeFromDateTime` retains the local clock's nanoseconds. These share one Go type rather than PHP's separate `PreciseTime` subclass.

`Hours()`, `Minutes()`, `Compare(other)`, `Diff(other)`, `Data()` and `WithData()` support clock operations. `Diff` returns the signed duration from this time to the other. `OnDate(date)` applies the wall time to a calendar date. `Format(layout, location)` uses Go layouts, with a leading `15:04` preserving `24:00`. `String()` always returns `HH:MM`.

Differences from PHP
--------------------------------------------------------------------------------------------------------------------

- Go uses explicit errors and `(value, bool)` for absent ranges, not exceptions or null.
- `Config` and parser callbacks replace mutable setters. `Config.Now` replaces custom date classes used to control the current time. Returned dates are always `time.Time` values.
- Metadata can contain arbitrary Go values. JSON input naturally restricts metadata to JSON types.
- Filters are ordered Go functions in `Config.Filters`, not executable entries in a JSON exceptions object.
- Collection callbacks become normal loops over returned maps or slices.
- Overlap checks are symmetric. Reversed date ranges and arbitrary separators are rejected rather than relying on PHP's date parser.
- Formatting uses Go layouts, and ambiguous or nonexistent local times follow Go's `time.Date` behavior.
- PHP Carbon and OpenStreetMap adapters are not Go dependencies. Convert those formats into `Config` or schema.org JSON in the application.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
