period

package module
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 11, 2024 License: MIT Imports: 8 Imported by: 0

README

Period

Go Reference Go Report Card codecov

Purpose

Library that extends time.Duration from standard library with years, months and days

Without approximations

Without regular expressions

Compatible with time.Duration

Usage

Example:

package main

import (
    "fmt"
    "time"

    "github.com/akramarenkov/period"
)

func main() {
    period, found, err := period.Parse("2y3mo10d23h59m58s10ms30µs10ns")
    if err != nil {
        panic(err)
    }

    if !found {
        return
    }

    fmt.Println(period)
    fmt.Println(period.ShiftTime(time.Date(2023, time.April, 1, 0, 0, 0, 0, time.UTC)))
    // Output: 2y3mo10d23h59m58.01003001s
    // 2025-07-11 23:59:58.01003001 +0000 UTC
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrIncompleteNumber       = errors.New("incomplete named number")
	ErrInvalidExpression      = errors.New("invalid expression")
	ErrNumberUnitIsNotUnique  = errors.New("named number unit is not unique")
	ErrUnexpectedNumberFormat = errors.New("unexpected number format")
	ErrUnexpectedSymbol       = errors.New("unexpected symbol")
)
View Source
var (
	ErrEmptyUnitModifier       = errors.New("unit modifier is empty")
	ErrInvalidUnit             = errors.New("invalid unit")
	ErrMissingUnit             = errors.New("missing unit")
	ErrMissingUnitModifier     = errors.New("unit modifier is missing")
	ErrUnexpectedUnit          = errors.New("unexpected unit")
	ErrUnitModifierIsNotUnique = errors.New("unit modifier is not unique")
)
View Source
var (
	ErrNumberBaseIsZero = errors.New("number base is zero")
)
View Source
var (
	ErrUnexpectedDigit = errors.New("unexpected digit")
)
View Source
var (
	ErrUnexpectedNumberSign = errors.New("unexpected number sign")
)
View Source
var (
	ErrValueOverflow = errors.New("value overflow")
)

Functions

func IsValidUnitsTable

func IsValidUnitsTable(units UnitsTable) error

Validates units table.

Types

type Opts added in v1.1.0

type Opts struct {
	// Provides more accurate parsing in the presence of non-significant zeros in
	// the input string
	ExtraZerosResistance bool
	// Disables validates units table
	NotValidateUnits bool
	Units            UnitsTable
	// Enables checking for units uniqueness in the input string
	UnitsMustBeUnique bool
}

type Period

type Period struct {
	// contains filtered or unexported fields
}

func New

func New() Period

Creates empty Period instance with default units table.

func NewCustom

func NewCustom(units UnitsTable) (Period, error)

Creates empty Period instance with custom units table.

Units table validates before create instance.

func NewCustomUnsafe

func NewCustomUnsafe(units UnitsTable) Period

Creates empty Period instance with custom units table.

Units table not validates before create instance. Use IsValidUnitsTable() yourself before creates instance.

func NewWithOpts added in v1.1.0

func NewWithOpts(opts Opts) (Period, error)

Creates empty Period instance with options.

func Parse

func Parse(input string) (Period, bool, error)

Creates Period instance from input string with default units table.

Example
package main

import (
	"fmt"
	"time"

	"github.com/akramarenkov/period"
)

func main() {
	period, found, err := period.Parse("2y3mo10d23h59m58s10ms30µs10ns")
	if err != nil {
		panic(err)
	}

	if !found {
		return
	}

	fmt.Println(period)
	fmt.Println(period.ShiftTime(time.Date(2023, time.April, 1, 0, 0, 0, 0, time.UTC)))
}
Output:

2y3mo10d23h59m58.01003001s
2025-07-11 23:59:58.01003001 +0000 UTC

func ParseCustom

func ParseCustom(input string, units UnitsTable) (Period, bool, error)

Creates Period instance from input string with custom units table.

Units table validates before create instance.

func ParseCustomUnsafe

func ParseCustomUnsafe(input string, units UnitsTable) (Period, bool, error)

Creates Period instance from input string with custom units table.

Units table not validates before create instance. Use IsValidUnitsTable() yourself before creates instance.

func ParseWithOpts added in v1.1.0

func ParseWithOpts(input string, opts Opts) (Period, bool, error)

Creates Period instance from input string with options.

func (*Period) AddDate

func (prd *Period) AddDate(years int, months int, days int) error

Increases or decreases value of years, months and days.

func (*Period) AddDuration

func (prd *Period) AddDuration(duration time.Duration) error

Increases or decreases duration part.

It is not Period duration, it is part of Period with value of hours, minutes, seconds and etc.

func (Period) Days

func (prd Period) Days() int

Returns days separately.

func (Period) Duration

func (prd Period) Duration() time.Duration

Returns duration part separately.

It is not Period duration, it is part of Period with value of hours, minutes, seconds and etc.

For get Period duration use RelativeDuration().

func (Period) IsNegative

func (prd Period) IsNegative() bool

Returns Period sign (negative or positive).

func (Period) Months

func (prd Period) Months() int

Returns months separately.

func (*Period) Parse added in v1.1.0

func (prd *Period) Parse(input string) (bool, error)

func (Period) RelativeDuration

func (prd Period) RelativeDuration(base time.Time) time.Duration

Calculates Period value in time.Duration.

Base time is necessary because shift to days, months and years not deterministic and depends on time around which it occurs.

func (*Period) SetDays

func (prd *Period) SetDays(days int) error

Sets days separately.

func (*Period) SetDuration

func (prd *Period) SetDuration(duration time.Duration) error

Sets duration part separately.

It is not Period duration, it is part of Period with value of hours, minutes, seconds and etc.

func (*Period) SetMonths

func (prd *Period) SetMonths(months int) error

Sets months separately.

func (*Period) SetNegative

func (prd *Period) SetNegative(negative bool)

Sets Period sign (negative or positive).

func (*Period) SetYears

func (prd *Period) SetYears(years int) error

Sets years separately.

func (Period) ShiftTime

func (prd Period) ShiftTime(base time.Time) time.Time

Shifts base time to Period value.

func (Period) String

func (prd Period) String() string

Converts Period value into string.

func (Period) Years

func (prd Period) Years() int

Returns years separately.

type Unit

type Unit int
const (
	UnitUnknown Unit = iota
	UnitYear
	UnitMonth
	UnitDay
	UnitHour
	UnitMinute
	UnitSecond
	UnitMillisecond
	UnitMicrosecond
	UnitNanosecond
)

type UnitsTable

type UnitsTable map[Unit][]string

Units table for custom parsing and converting to string.

Must contains all Unit constants (except UnitUnknown) and at least one modifier for each unit of measure. First modifier for unit is a default modifier that used when converting to string.

Default units:

  • y - years;
  • mo - months;
  • d - days;
  • h - hours;
  • m - minutes;
  • s - seconds;
  • ms - milliseconds;
  • us, µs - microseconds;
  • ns - nanoseconds.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL