isoduration

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2024 License: BSD-3-Clause Imports: 8 Imported by: 0

README

ISODURATION

It's multifunctional and fast a Go module for parsing ISO 8601 duration format

Why use?

ISO 8601 duration format is a convenient format for recording the duration of something, for example, you can use this format in your configurations to indicate the duration of the wait or for time-based events.

Features

  • fast parsing of raw strings in ISO 8601 duration format
  • convenient tools for obtaining and reverse conversion of time.Duration
  • possibility to get each period and time element in float64 format
  • human-readable errors open for import and comparison
  • yaml serialization and deserialization
  • json serialization and deserialization

Installation

go get github.com/MyBlackJay/isoduration

Example

Code:
package main

import (
	"encoding/json"
	"fmt"
	"github.com/MyBlackJay/isoduration"
	"gopkg.in/yaml.v3"
	"time"
)

type Config struct {
	FlushThresholdDuration *isoduration.Duration `yaml:"flush_threshold_duration" json:"flush_threshold_duration"`
}

type Main struct {
	Config Config `yaml:"config" json:"config"`
}

func yamlToStruct() {
	yml := `
config:
  flush_threshold_duration: PT30M30S
`
	m := &Main{}

	if err := yaml.Unmarshal([]byte(yml), m); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(m.Config.FlushThresholdDuration.ToTimeDuration())
}

func jsonToStruct() {
	jsn := `{"config": {"flush_threshold_duration": "PT30M30S"}}`
	m := &Main{}

	if err := json.Unmarshal([]byte(jsn), m); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(m.Config.FlushThresholdDuration)
}

func structToYaml() {
	tp := &Main{
		Config: Config{
			FlushThresholdDuration: isoduration.NewDuration(1, 1, 5, 0, 1, 30, 12, true),
		},
	}

	if out, err := yaml.Marshal(tp); err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println(string(out))
	}

}

func structToJson() {
	tp := &Main{
		Config: Config{
			FlushThresholdDuration: isoduration.NewDuration(1, 1, 5, 0, 1, 30, 12, true),
		},
	}

	if out, err := json.Marshal(tp); err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println(string(out))
	}
}

func timeDelta() {
	str := "PT10H5M"
	strNeg := "-PT10H5M"
	now := time.Now()

	td := time.Hour * 20

	iso, _ := isoduration.ParseDuration(str)
	isoNeg, _ := isoduration.ParseDuration(strNeg)

	fmt.Println(td - iso.ToTimeDuration())
	fmt.Println(td - isoNeg.ToTimeDuration())
	fmt.Println(now.Add(iso.ToTimeDuration()).UTC())
	fmt.Println(now.Add(isoNeg.ToTimeDuration()).UTC())

}

func fromTimeDuration() {
	dur := (time.Hour * isoduration.DayHours * isoduration.YearDays * 2) + (60 * time.Hour) + (30 * time.Second)
	v := isoduration.NewFromTimeDuration(dur)
	c := isoduration.FormatTimeDuration(dur)

	fmt.Println(v, c)
}

func main() {
	yamlToStruct() // 30m30s
	jsonToStruct() // 30m35s
	structToYaml() // config:
	//                  flush_threshold_duration: -P1Y1M5DT1H30M12S
	structToJson()     // {"config":{"flush_threshold_duration":"-P1Y1M5DT1H30M12S"}}
	timeDelta()        // 9h55m0s | 30h5m0s | 2024-01-19 21:25:38.660823592 +0000 UTC | 2024-01-19 01:15:38.660823592 +0000 UTC
	fromTimeDuration() // P2Y2DT12H30S P2Y2DT12H30S
}

Documentation

Index

Constants

View Source
const (
	// PERIOD is constant that defines period designators
	PERIOD = 'P'
	// TIME is constant that defines time designators
	TIME = 'T'

	// YEAR is constant that defines year designators
	YEAR = 'Y'
	// MONTH is constant that defines month designators
	MONTH = 'M'
	// WEEK is constant that defines week designators
	WEEK = 'W'
	// DAY is constant that defines day designators
	DAY = 'D'
	// HOUR is constant that defines hour designators
	HOUR = 'H'
	// MINUTE is constant that defines minute designators
	MINUTE = 'M'
	// SECOND is constant that defines second designators
	SECOND = 'S'

	// DayHours is constant that defines number of hours in a day
	DayHours = 24
	// WeekDays is constant that defines number of days in a week
	WeekDays = 7
	// YearDays is constant that defines number of days in a year
	YearDays = 365
	// MonthDays is constant that defines number of days in a month
	MonthDays = YearDays / 12
)

Variables

View Source
var IsNotIsoFormatError = errors.New("incorrect ISO 8601 duration format")

IsNotIsoFormatError occurs when parsing a string in ISO 8601 duration format, the error cannot be clearly identified

View Source
var PeriodIsEmptyError = errors.New("incorrect ISO 8601 P duration format, designator P found, but value is empty")

PeriodIsEmptyError occurs when a period designator is found in a line, but its value is not found For example: P

View Source
var TimeIsEmptyError = errors.New("incorrect ISO 8601 T duration format, designator T found, but value is empty")

TimeIsEmptyError occurs when a time designator is found in a line, but its value is not found For example: P10YT

Functions

func FormatTimeDuration

func FormatTimeDuration(d time.Duration) string

FormatTimeDuration represents time.Duration as a string in ISO 8601 duration format Affect: This may have some rounding inaccuracies

Types

type DesignatorMetError

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

DesignatorMetError occurs when this designator has already been processed previously. Affect: if you write string like PT10H0M10M it defines value as 10 For example: P1Y5Y

func NewDesignatorMetError

func NewDesignatorMetError(designator rune) *DesignatorMetError

NewDesignatorMetError creates new DesignatorMetError

func (*DesignatorMetError) Error

func (i *DesignatorMetError) Error() string

Error defines error output

func (*DesignatorMetError) Is

func (i *DesignatorMetError) Is(err error) bool

Is checks for object matching

type DesignatorNotFoundError

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

DesignatorNotFoundError occurs when there is no designator in the line after the token For example P10T10H.

func NewDesignatorNotFoundError

func NewDesignatorNotFoundError(state rune, after string) *DesignatorNotFoundError

NewDesignatorNotFoundError creates new DesignatorNotFoundError

func (*DesignatorNotFoundError) Error

func (i *DesignatorNotFoundError) Error() string

Error defines error output

func (*DesignatorNotFoundError) Is

func (i *DesignatorNotFoundError) Is(err error) bool

Is checks for object matching

type DesignatorValueNotFoundError

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

DesignatorValueNotFoundError occurs when no value is found for the designator For example: PT1HM

func NewDesignatorValueNotFoundError

func NewDesignatorValueNotFoundError(state, designator rune) *DesignatorValueNotFoundError

NewDesignatorValueNotFoundError creates new DesignatorValueNotFoundError

func (*DesignatorValueNotFoundError) Error

Error defines error output

func (*DesignatorValueNotFoundError) Is

Is checks for object matching

type Duration

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

Duration is basic duration structure

func MustParseDuration

func MustParseDuration(duration string) *Duration

MustParseDuration is the main method for parsing a string in ISO format. Returns *Duration. If the string cannot be parsed, it returns a panic For example: P10Y5M2W1DT1H1.5M50S or -P10Y5M2W1DT1H1.5M50S

func NewDuration

func NewDuration(years, months, days, weeks, hours, minutes, seconds float64, isNegative bool) *Duration

NewDuration creates new *Duration based on time and period marks

func NewFromTimeDuration

func NewFromTimeDuration(t time.Duration) *Duration

NewFromTimeDuration creates new *Duration based on time.Duration Affect: This may have some rounding inaccuracies

func ParseDuration

func ParseDuration(duration string) (*Duration, error)

ParseDuration is the main method for parsing a string in ISO format. Returns *Duration and an error if the string could not be parsed For example: P10Y5M2W1DT1H1.5M50S or -P10Y5M2W1DT1H1.5M50S

func (*Duration) Days

func (d *Duration) Days() float64

Days returns days from *PeriodDuration

func (*Duration) Hours

func (d *Duration) Hours() float64

Hours returns hours from *TimeDuration

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON designed to deserialize *Duration to a string in ISO 8601 duration format, defined in user code via the json library

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (interface{}, error)

MarshalYAML designed to deserialize *Duration to a string in ISO 8601 duration format, defined in user code via the gopkg.in/yaml.v3 library

func (*Duration) Minutes

func (d *Duration) Minutes() float64

Minutes returns minutes from *TimeDuration

func (*Duration) Months

func (d *Duration) Months() float64

Months returns months from *PeriodDuration

func (*Duration) Seconds

func (d *Duration) Seconds() float64

Seconds returns seconds from *TimeDuration

func (*Duration) String

func (d *Duration) String() string

ToTimeDuration turns *Duration into a string in ISO 8601 duration format

func (*Duration) ToTimeDuration

func (d *Duration) ToTimeDuration() time.Duration

ToTimeDuration turns *Duration into time.Duration

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(source []byte) error

UnmarshalJSON designed to serialize a string in ISO 8601 duration format to *Duration, defined in user code via the json library

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML designed to serialize a string in ISO 8601 duration format to *Duration, defined in user code via the gopkg.in/yaml.v3 library

func (*Duration) Weeks

func (d *Duration) Weeks() float64

Weeks returns weeks from *PeriodDuration

func (*Duration) Years

func (d *Duration) Years() float64

Years returns years from *PeriodDuration

type IncorrectDesignatorError

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

IncorrectDesignatorError occurs when an unknown designator is encountered in the line. For example: PT10Y or P1V

func NewIncorrectDesignatorError

func NewIncorrectDesignatorError(state, designator rune) *IncorrectDesignatorError

NewIncorrectDesignatorError creates new IncorrectDesignatorError

func (*IncorrectDesignatorError) Error

func (i *IncorrectDesignatorError) Error() string

Error defines error output

func (*IncorrectDesignatorError) Is

func (i *IncorrectDesignatorError) Is(err error) bool

Is checks for object matching

type IncorrectIsoFormatError

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

IncorrectIsoFormatError occurs when a token is found in a string that cannot be converted to the float64 type For example: P10,5Y

func NewIncorrectIsoFormatError

func NewIncorrectIsoFormatError(in string) *IncorrectIsoFormatError

NewIncorrectIsoFormatError creates new IncorrectIsoFormatError

func (*IncorrectIsoFormatError) Error

func (i *IncorrectIsoFormatError) Error() string

Error defines error output

func (*IncorrectIsoFormatError) Is

func (i *IncorrectIsoFormatError) Is(err error) bool

Is checks for object matching

type PeriodDuration

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

PeriodDuration is period duration marks

type TimeDuration

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

TimeDuration is time duration marks

Jump to

Keyboard shortcuts

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