Usage | period-go | Spatie       

 SPATIE  

period-go
=========

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Period-go](https://spatie.be/docs/period-go/v1)  Usage

 Version   v1      

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

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

 Usage
=====

###  On this page 

1. [ Creating periods ](#content-creating-periods)
2. [ Reference ](#content-reference)
3. [ Collections ](#content-collections)
4. [ Compatibility ](#content-compatibility)
5. [ Visualizing periods ](#content-visualizing-periods)

Creating periods
--------------------------------------------------------------------------------------------------------

You're encouraged to create periods using `Parse` for strings or `New` for `time.Time` values:

```
p, err := period.Parse("2021-01-01", "2021-01-31")
if err != nil {
    return err
}
```

Both constructors round dates down. The default precision is `period.Day` and the default boundaries are `period.ExcludeNone`. Use `NewExact` to preserve unrounded dates and fractional seconds, explicitly providing precision and boundaries.

Before discussing the API provided by this package, it's important to understand both how precision and boundaries are used.

### Precision

Date precision is of utmost importance if you want to reliably compare two periods. The following example:

> Given two periods, `[2021-01-01, 2021-01-15]` and `[2021-01-15, 2021-01-31]`, do they overlap?

At first glance the answer is "yes", they overlap on `2021-01-15`. But what if the first period ends at `2021-01-15 10:00:00`, while the second starts at `2021-01-15 15:00:00`? Now they don't anymore!

This is why this package requires you to specify a precision with each period. Only periods with the same precision can be compared, except `ContainsPeriod`.

A more in-depth explanation on why precision is so important can be found [here](https://stitcher.io/blog/comparing-dates). A period's precision can be specified when constructing that period:

```
p, err := period.Parse("2021-01-01", "2021-02-01",
    period.WithPrecision(period.Day),
)
```

The available options, from coarsest to finest, are `period.Year`, `period.Month`, `period.Day`, `period.Hour`, `period.Minute` and `period.Second`.

### Boundaries

By default, period comparisons are done with included boundaries. This means that these two periods overlap:

```
a, err := period.Parse("2021-01-01", "2021-02-01")
if err != nil {
    return err
}
b, err := period.Parse("2021-02-01", "2021-02-28")
if err != nil {
    return err
}
overlaps, err := a.OverlapsWith(b) // true, nil
```

The length of a period will also include both boundaries. A period from `2021-01-01` through `2021-01-31` has length `31`. It's possible to override the boundary behaviour:

```
a, err := period.Parse("2021-01-01", "2021-02-01",
    period.WithBoundaries(period.ExcludeEnd),
)
```

The four types of boundary exclusion are `period.ExcludeNone`, `period.ExcludeStart`, `period.ExcludeEnd` and `period.ExcludeAll`. Excluded endpoints move inward by one precision unit.

For day, hour, minute and second precision, `Length` returns `0` when boundary exclusions move the included start after the included end and iteration yields no dates:

```
empty, err := period.Parse("2021-01-01", "2021-01-01",
    period.WithBoundaries(period.ExcludeAll),
)
if err != nil {
    return err
}
fmt.Println(empty.Length()) // 0
```

Month and year lengths use the period's iterator. Other lengths retain their arithmetic when dates are yielded, including manually constructed periods with fractional seconds. Length and iterator count are not generally interchangeable across daylight-saving transitions.

Reference
-----------------------------------------------------------------------------------

The `Period` type has methods to compare periods and collections of periods. Start and end date comparisons use the period's precision and its included boundaries:

- `StartsBefore(time.Time) bool`, `StartsBeforeOrAt(time.Time) bool`
- `StartsAfter(time.Time) bool`, `StartsAfterOrAt(time.Time) bool`
- `StartsAt(time.Time) bool`
- `EndsBefore(time.Time) bool`, `EndsBeforeOrAt(time.Time) bool`
- `EndsAfter(time.Time) bool`, `EndsAfterOrAt(time.Time) bool`
- `EndsAt(time.Time) bool`
- `OverlapsWith(Period) (bool, error)` determines whether periods overlap
- `TouchesWith(Period) (bool, error)` determines whether periods are adjacent without overlap
- `Contains(time.Time) bool` determines whether a date lies within the period
- `ContainsPeriod(Period) bool` determines whether another period is contained, permitting different precisions
- `Equals(Period) (bool, error)` compares included endpoint timestamps at whole-second resolution

Comparisons between periods with different precisions return `ErrPrecisionMismatch`, except containment. Use `errors.Is` to check this and the other exported errors.

### `Overlap(others ...Period) (*Period, error)`

Overlaps two or more periods on each other. The resulting period is the intersection of all periods combined. No others or no shared overlap returns `nil, nil`. The result retains the receiver's boundary style.

![Overlap](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-overlap.png)

### `OverlapAny(others ...Period) (Collection, error)`

Overlaps two or more periods on each other. Each pairwise overlap is added to a collection which will be returned as the final result. Input order and duplicate overlaps are preserved.

![Overlap any](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-overlap-any.png)

### `Subtract(others ...Period) (Collection, error)`

Subtracts one or more periods from the main period. This is the inverse operation of overlap. Results retain the receiver's boundary style. No others returns a collection containing the receiver.

![Subtract](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-subtract.png)

### `Gap(other Period) (*Period, error)`

Gets the gap between two periods, or `nil, nil` if the periods overlap or touch. Gap periods have inclusive boundaries.

![Gap](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-gap.png)

### `DiffSymmetric(other Period) (Collection, error)`

Performs a [symmetric diff](https://www.math-only-math.com/symmetric-difference-using-Venn-diagram.html)between two periods, keeping dates present in either but not both.

![Symmetric difference](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-diff-symmetric.png)

### `Renew() (Period, error)`

Renews the current period, creating a new period with the same calendar duration that happens after the current period. The new period keeps the original boundary style, so excluded boundaries can change its included length.

![Renew](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/period-renew.png)

### Getters

- `IsStartIncluded() bool`, `IsStartExcluded() bool`
- `IsEndIncluded() bool`, `IsEndExcluded() bool`
- `Start() time.Time`, `IncludedStart() time.Time`
- `End() time.Time`, `IncludedEnd() time.Time`
- `CeilingEnd(precision ...Precision) (time.Time, error)` returns the included end's last second, defaulting to the period's precision. An optional coarser precision is allowed, but a finer precision returns `ErrCeilingPrecision`
- `Length() int64`
- `Duration() Duration`
- `Precision() Precision`
- `Boundaries() Boundaries`

Use `String()` for the original endpoints and boundary notation, such as `[2021-01-01,2021-01-31]`. `FromString` parses this notation and infers precision. The notation has no timezone, so parsing uses UTC.

`Duration` measures the calendar interval between included endpoints, without the extra precision unit counted by `Length`. Use `Equals`, `IsLargerThan`, `IsSmallerThan` or `CompareTo` to compare durations. `CompareTo` adds both intervals to the same current UTC second. `CompareAt` accepts a caller-supplied reference time and compares at whole-second resolution.

PHP's `Duration.Equals` also considers durations with equal total day counts equal, even when their hour counts differ. This port preserves that behaviour. For a consistent ordering, use `CompareAt(other, reference) == 0` instead. Calendar months are not fixed durations, so a month can compare shorter or longer than thirty days depending on the reference date.

Collections
-----------------------------------------------------------------------------------------

The `Collection` type is an ordered slice of periods and has some useful methods on its own. Use `period.Collection{a, b}` to create one.

### `OverlapAll(others ...Collection) (Collection, error)`

Overlaps all collection periods on each other, preserving both collections' insertion order and duplicate pairwise overlaps.

![Collection overlap all](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-overlap-all.png)

### `Subtract(others ...Period) (Collection, error)`

Subtracts a period or a collection of periods from a period collection. Pass `others...` to subtract another collection.

![Collection subtract](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-subtract.png)

### `Boundaries() (*Period, error)`

Creates a new inclusive period representing the outer boundaries of the collection. An empty collection returns `nil, nil`.

![Collection boundaries](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-boundaries.png)

### `Gaps() (Collection, error)`

Gives the gaps for all periods within this collection.

![Collection gaps](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-gaps.png)

### `Intersect(intersection Period) (Collection, error)`

Intersects the given period with every period within a collection. The result is a new collection of overlapping periods. When there's no overlap, the original period is discarded.

![Collection intersect](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-intersect.png)

### `Union() (Collection, error)`

Merges all periods in the collection with overlapping or touching ranges. The returned ranges have inclusive boundaries.

![Collection union](https://fls-a2e2b4d6-b344-41b9-abd1-6c06196a36b3.laravel.cloud/docs/period-go/v1/img/collection-union.png)

### Utilities

- `Add(periods ...Period) Collection` copies the collection with periods appended
- `Map(func(Period) Period) Collection` maps periods into a new collection
- `period.Reduce[T](Collection, T, func(T, Period) T) T` folds periods in input order
- `Filter(func(Period) bool) Collection` keeps matching periods
- `IsEmpty() bool`
- `Sort() Collection` is a stable sort by included start
- `Unique() Collection` removes duplicate string representations, keeping the last value at its first position

`Add`, `Map`, `Filter`, `Sort` and `Unique` return new slices without changing the original collection. Keep the result when chaining these methods:

```
ordered := periods.Unique().Sort()
```

Use `len`, indexing, `append`, `slices.Delete` and `range` for ordinary slice operations. Unlike PHP array keys, Go slice indices are always contiguous. Copy a collection with `slices.Clone` before changing its entries if another caller shares the underlying slice. Period values themselves remain immutable.

Compatibility
-----------------------------------------------------------------------------------------------

You can construct a `Period` from any Go `time.Time` value:

```
start := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2021, time.January, 31, 0, 0, 0, 0, time.UTC)
p, err := period.New(start, end)
```

`Parse` accepts ISO years, months, dates, local date-times and RFC3339 timestamps. Dates without an offset use UTC, never the process timezone. To keep a named timezone, pass `time.Time` values in that location to `New`, or use `ParseInLocation(layout, start, end, location, options...)` with a Go time layout. This follows Go's parsing rules, including its resolution of ambiguous input times. Supply an offset-bearing instant to `New` when a particular repeated hour is required. Invalid dates return errors instead of overflowing to the next month.

Round dates, find their ceiling or move one precision unit with `Precision.Round`, `Ceiling`, `Increment` and `Decrement`. Month arithmetic overflows short months, matching PHP and `time.AddDate`. For example, January 31 plus one month becomes March 3 in a non-leap year. `Precision.Diff` returns a signed calendar `Interval`, whose `AddTo` applies calendar fields, including clock fields, in the destination location.

You can iterate a `Period` with the precision specified on creation:

```
for date := range p.Dates() {
    fmt.Println(date.Format(time.DateOnly))
}
```

Iteration is lazy and supports early `break`. Like PHP's `DatePeriod`, iteration advances calendar fields. It can skip the second occurrence of a repeated hour, while `Length` counts both occurrences using elapsed seconds at sub-day precision. Day precision uses calendar-day counts, including days with a missing midnight.

### Custom date iteration

PHP subclasses can override `getIterator`. Use `WithIterator` for that extension point in Go. The callback receives the period being iterated and returns `iter.Seq[time.Time]`. Month and year `Length` use this iterator too. Derived period operations retain the callback. Call `CalendarDates` inside the callback to get the built-in iterator without recursion:

```
weekdays := period.WithIterator(func(p period.Period) iter.Seq[time.Time] {
    return func(yield func(time.Time) bool) {
        for date := range p.CalendarDates() {
            if date.Weekday() == time.Saturday || date.Weekday() == time.Sunday {
                continue
            }
            if !yield(date) {
                return
            }
        }
    }
})
```

Pass `weekdays` to `New` or `Parse`. Like PHP, day and sub-day `Length` still use their arithmetic rather than this callback. Calendar operations do not reinterpret overlap and subtraction as business-day operations. Outer collection boundaries are base inclusive periods, as in PHP, and do not inherit an entry's iterator.

The port uses composition and callbacks rather than arbitrary class inheritance. The package has no models, jobs or configurable profile classes.

Visualizing periods
-----------------------------------------------------------------------------------------------------------------

You can visualize one or more periods as well as collections to see how they relate to one another. Supply ordered named rows, wrapping a single period in a one-entry collection:

```
output, err := period.Visualize(27,
    period.Block{Name: "A", Periods: period.Collection{a}},
    period.Block{Name: "B", Periods: period.Collection{b}},
    period.Block{Name: "OVERLAP", Periods: overlaps},
)
```

The width controls the bars only, not the labels. The output is a string with one line per row and trailing spaces retained. A point-only range displays `=`. Empty input returns an empty string, and nonpositive width returns an error. Those cases are defined explicitly rather than inheriting PHP's division-by-zero behaviour for zero-length outer ranges.

See [testing](testing) for tests and executable Go examples.

 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)
