Package trn introduces a Range type with useful methods to perform complex
operations over time ranges.
go get -u github.com/cappuccinotm/trn
rng := trn.New(time.Now(), 3 * time.Hour, trn.In(time.UTC))
betweenRng := trn.Between(time.Now(), time.Now().Add(3 * time.Hour), trn.In(time.UTC))For more examples see test file.
- Make UTC and opts tests work in UTC location
-
func New(start time.Time, duration time.Duration, opts ...Option) RangeCreates a new
Rangewith start at the given time and with the given duration. -
func Between(start, end time.Time, opts ...Option) (Range, error)Creates a new
Rangewithin the given time range.Betweenuses the location of thestarttime for the range. Returns ErrStartAfterEnd if the start time is later than the end. -
func (r Range) Stratify(duration time.Duration, interval time.Duration) ([]Range, error)Slices the range into smaller ones with fixed
durationand fixedintervalbetween their starts. In case if the last interval doesn't fit into the given duration,Stratifywon't return it. Returns ErrZeroDurationInterval if the provided duration or interval is less or equal to zero.
-
func (r Range) Split(duration time.Duration, interval time.Duration) ([]Range, error)Slices the range into smaller ones with fixed
durationand fixedintervalbetween the end of the one range and start of next range. In case if the last interval doesn't fit into the given duration,Splitwon't return it. Returns ErrZeroDurationInterval if the provided duration is less or equal to zero.
-
func (r Range) Truncate(bounds Range) RangeCuts the start and the end of the range to fit the given
bounds.
MergeOverlappingRanges(ranges []Range) []Range
-
func (r Range) Flip(ranges []Range) []RangeFlips the given
rangeswithin the given period (r).The boundaries of the given ranges are considered to be inclusive, which means that the flipped ranges will start or end at the exact nanosecond where the boundary from the input starts or ends.
Note: for the sake of safety, ranges are being merged before flip to ensure the correct working of method.
-
func Intersection(ranges []Range) RangeReturns the range, which is common for all the given ranges.
There are some other non-algorithmic methods, which you can see in the reference.
String method formats the range in format [start time, end time], where the
times are formatted with the next template:
const defaultRangeFmt = "2006-01-02 15:04:05.999999999 -0700 MST"The code was extracted from existing project and still under development. Until v1.x released the API may change.