duration

package
v1.19.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 12 Imported by: 0

README

Duration Package

Go Version GoDoc

Extended duration handling with days support, multiple encoding formats, and big integer durations for very large time intervals.

AI Disclaimer (EU AI Act Article 50.4): AI assistance was used solely for testing, documentation, and bug resolution under human supervision.


Table of Contents


Overview

The duration package provides two complementary duration types:

  1. Standard Duration - Extended time.Duration with days support
  2. Big Duration - Large durations beyond time.Duration limits (>290 years)
Design Philosophy
  • Extended Syntax: Support for days notation (d) in duration strings
  • Type Safety: Compile-time safety with type wrappers
  • Interoperability: JSON, YAML, TOML, CBOR, and text encoding
  • Flexibility: Convert between duration types seamlessly
  • Range Generation: PID controller-based smooth transitions

Key Features

Standard Duration
Feature Description
Extended Parsing Parse durations with days (5d23h15m13s)
Multiple Formats JSON, YAML, TOML, CBOR, text encoding
Viper Integration Automatic configuration decoding
Arithmetic Add, subtract, multiply, divide durations
Truncation Truncate to days, hours, minutes, etc.
Range Generation PID controller-based ranges
Thread-Safe Safe for concurrent use
Big Duration
Feature Description
Large Durations Support durations >290 years (time.Duration limit)
int64 Seconds Based on seconds (not nanoseconds)
Max Duration ~106 trillion days (~292 billion years)
Same API Compatible API with standard duration
Type Conversion Convert to/from time.Duration, int64, float64

Architecture

Package Structure
duration/
├── interface.go         # Standard duration (time.Duration wrapper)
├── parse.go            # Parsing logic with days support
├── format.go           # String formatting
├── encode.go           # JSON/YAML/TOML/CBOR encoding
├── operation.go        # Arithmetic operations
├── truncate.go         # Truncation helpers
├── model.go            # Core implementation
│
└── big/                # Big duration sub-package
    ├── interface.go    # Large duration (int64 seconds)
    ├── parse.go        # Parsing for big durations
    ├── format.go       # Formatting for big durations
    ├── encode.go       # Encoding for big durations
    ├── operation.go    # Arithmetic for big durations
    ├── truncate.go     # Truncation for big durations
    └── model.go        # Big duration implementation
Type System
┌─────────────────────────────────────────────────────┐
│                 Duration Types                       │
│                                                      │
│  ┌────────────────────┐      ┌────────────────────┐│
│  │  duration.Duration │      │   big.Duration     ││
│  │                    │      │                    ││
│  │  Based on:         │      │  Based on:         ││
│  │  time.Duration     │      │  int64 (seconds)   ││
│  │  (int64 nanos)     │      │                    ││
│  │                    │      │                    ││
│  │  Range:            │      │  Range:            ││
│  │  ±290 years        │      │  ±292B years       ││
│  │                    │      │                    ││
│  │  Precision:        │      │  Precision:        ││
│  │  1 nanosecond      │      │  1 second          ││
│  └────────────────────┘      └────────────────────┘│
│           │                            │            │
│           └────────────┬───────────────┘            │
│                        ▼                             │
│  ┌──────────────────────────────────────────────┐  │
│  │         Common Features                      │  │
│  │  - Days notation (5d23h15m)                 │  │
│  │  - Multiple encodings (JSON, YAML, etc.)    │  │
│  │  - Arithmetic operations                    │  │
│  │  - Truncation & rounding                    │  │
│  │  - PID-based range generation               │  │
│  │  - Viper integration                        │  │
│  └──────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘

Conversion Flow:
  string ←→ Duration ←→ time.Duration ←→ big.Duration
         ←→ JSON/YAML/TOML/CBOR ←→

Installation

# Standard duration
go get github.com/nabbar/golib/duration

# Big duration
go get github.com/nabbar/golib/duration/big

Quick Start

Standard Duration
package main

import (
    "fmt"
    "github.com/nabbar/golib/duration"
)

func main() {
    // Parse duration with days
    d, _ := duration.Parse("5d23h15m13s")
    fmt.Println(d.String())  // Output: 5d23h15m13s
    
    // Create durations
    timeout := duration.Days(2) + duration.Hours(3)
    fmt.Println(timeout.String())  // Output: 2d3h
    
    // Convert to time.Duration
    std := timeout.Time()
    fmt.Println(std)  // Output: 51h0m0s
    
    // Truncate
    days := timeout.TruncateDays()
    fmt.Println(days.String())  // Output: 2d
}
Big Duration
package main

import (
    "fmt"
    durbig "github.com/nabbar/golib/duration/big"
)

func main() {
    // Very large duration (beyond time.Duration limits)
    d := durbig.Days(1000000)  // 1 million days
    fmt.Println(d.String())  // Output: 1000000d
    
    // Parse large duration
    large, _ := durbig.Parse("365000d")  // ~1000 years
    fmt.Println(large.String())
    
    // Arithmetic
    result := large + durbig.Days(100)
    fmt.Println(result.String())
}

Duration Package

Supported Units
const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
    Day                  = 24 * Hour  // Extension!
)
Parsing
// Parse various formats
d1, _ := duration.Parse("5h30m")         // 5h30m0s
d2, _ := duration.Parse("2d12h")         // 2d12h0m0s
d3, _ := duration.Parse("1.5h")          // 1h30m0s
d4, _ := duration.Parse("-3h")           // -3h0m0s

// Parse from bytes
d5, _ := duration.ParseByte([]byte("7d"))

// Convert from time.Duration
td := 5 * time.Hour
d6 := duration.ParseDuration(td)
Constructor Functions
d1 := duration.Nanoseconds(1000)    // 1µs
d2 := duration.Microseconds(1000)   // 1ms
d3 := duration.Milliseconds(1000)   // 1s
d4 := duration.Seconds(60)          // 1m
d5 := duration.Minutes(60)          // 1h
d6 := duration.Hours(24)            // 1d
d7 := duration.Days(7)              // 7d (1 week)

// Combine
timeout := duration.Days(1) + duration.Hours(2) + duration.Minutes(30)
Formatting
d := duration.Days(5) + duration.Hours(23) + duration.Minutes(15)

// String representation
fmt.Println(d.String())           // Output: 5d23h15m0s

// Convert to time.Duration
std := d.Time()

// Convert to nanoseconds (int64)
nanos := d.Nanoseconds()
Truncation & Rounding
d := duration.Parse("5d23h45m30s")

// Truncate
days := d.TruncateDays()        // 5d
hours := d.TruncateHours()      // 5d23h
minutes := d.TruncateMinutes()  // 5d23h45m

// Round
rounded := d.Round(duration.Hour)  // 6d (rounds to nearest hour)
Arithmetic Operations
d1 := duration.Hours(5)
d2 := duration.Hours(3)

sum := d1 + d2              // 8h
diff := d1 - d2             // 2h
product := d1 * 2           // 10h
quotient := d1 / 2          // 2h30m

// Comparison
if d1 > d2 {
    fmt.Println("d1 is longer")
}
Range Generation

Generate smooth transitions between durations using PID controller:

start := duration.Seconds(10)
end := duration.Minutes(5)

// With custom PID rates
rateP := 0.1
rateI := 0.01
rateD := 0.001
ranges := start.RangeTo(end, rateP, rateI, rateD)

// With default rates
rangesDef := start.RangeDefTo(end)

for _, d := range rangesDef {
    fmt.Println(d.String())
}

Big Duration Package

Constants
const (
    Second Duration = 1              // 1 second
    Minute          = 60 * Second    // 60 seconds
    Hour            = 60 * Minute    // 3600 seconds
    Day             = 24 * Hour      // 86400 seconds
)

// Maximum: ~106,751,991,167,300 days (~292 billion years)
Why Use Big Duration?

time.Duration Limitations:

  • Based on int64 nanoseconds
  • Maximum: ~290 years
  • Overflows for long-term scheduling

big.Duration Solutions:

  • Based on int64 seconds
  • Maximum: ~292 billion years
  • Perfect for astronomical calculations
  • No nanosecond precision needed
Creating Big Durations
import durbig "github.com/nabbar/golib/duration/big"

// Constructors
d1 := durbig.Seconds(86400)         // 1 day
d2 := durbig.Minutes(1440)          // 1 day
d3 := durbig.Hours(24)              // 1 day
d4 := durbig.Days(365)              // 1 year

// From float64 (seconds)
d5 := durbig.ParseFloat64(3600.5)   // 1h0m0.5s

// From time.Duration
td := 24 * time.Hour
d6 := durbig.ParseDuration(td)      // 1 day

// Very large
millennium := durbig.Days(365250)   // ~1000 years
Type Conversions
d := durbig.Days(7)

// To int64 (seconds)
seconds := d.Int64()  // 604800

// To uint64 (seconds, 0 if negative)
useconds := d.Uint64()  // 604800

// To float64 (seconds)
fseconds := d.Float64()  // 604800.0

// To time.Duration (if within range)
td, err := d.Duration()
if err != nil {
    // Duration too large for time.Duration
}

// To string
str := d.String()  // "7d"
Parsing
// Parse string
d1, _ := durbig.Parse("365d")        // 1 year
d2, _ := durbig.Parse("1000000d")    // 1 million days
d3, _ := durbig.Parse("5h30m")       // 5h30m
d4, _ := durbig.Parse("2.5h")        // 2h30m (fractional)

// Parse bytes
d5, _ := durbig.ParseByte([]byte("10d"))
Operations
d1 := durbig.Days(100)
d2 := durbig.Days(50)

// Arithmetic
sum := d1 + d2          // 150d
diff := d1 - d2         // 50d
product := d1 * 3       // 300d
quotient := d1 / 2      // 50d

// Comparison
if d1 > d2 {
    fmt.Println("d1 is longer")
}

// Absolute value
abs := durbig.Days(-5).Abs()  // 5d

// Truncation
t := durbig.Parse("7d12h30m")
days := t.TruncateDays()      // 7d
hours := t.TruncateHours()    // 7d12h

Encoding Support

Both duration types support multiple encoding formats:

JSON
type Config struct {
    Timeout duration.Duration `json:"timeout"`
    MaxAge  durbig.Duration   `json:"max_age"`
}

cfg := Config{
    Timeout: duration.Days(1),
    MaxAge:  durbig.Days(365),
}

// Marshal
data, _ := json.Marshal(cfg)
// {"timeout":"1d","max_age":"365d"}

// Unmarshal
var cfg2 Config
json.Unmarshal(data, &cfg2)
YAML
import "gopkg.in/yaml.v3"

type Config struct {
    Timeout duration.Duration `yaml:"timeout"`
}

// Marshal
data, _ := yaml.Marshal(Config{Timeout: duration.Hours(24)})
// timeout: 1d

// Unmarshal
var cfg Config
yaml.Unmarshal(data, &cfg)
TOML
import "github.com/pelletier/go-toml/v2"

type Config struct {
    Timeout duration.Duration `toml:"timeout"`
}

// Works with toml.Marshal/Unmarshal
CBOR
import "github.com/fxamacker/cbor/v2"

type Config struct {
    Timeout duration.Duration `cbor:"timeout"`
}

// Works with cbor.Marshal/Unmarshal
Text Encoding
d := duration.Days(5)

// Marshal
text, _ := d.MarshalText()
// []byte("5d")

// Unmarshal
var d2 duration.Duration
d2.UnmarshalText([]byte("5d"))

Viper Integration

Both packages provide decoder hooks for Viper configuration:

import (
    "github.com/spf13/viper"
    "github.com/nabbar/golib/duration"
    durbig "github.com/nabbar/golib/duration/big"
)

type Config struct {
    Timeout  duration.Duration
    MaxAge   durbig.Duration
}

func loadConfig() Config {
    v := viper.New()
    v.SetConfigFile("config.yaml")
    v.ReadInConfig()
    
    var cfg Config
    v.Unmarshal(&cfg, viper.DecodeHook(
        duration.ViperDecoderHook(),
        // Add other hooks as needed
    ))
    
    return cfg
}

config.yaml:

timeout: 2d3h
max_age: 365d

Performance

Memory Characteristics

Standard Duration:

  • Size: 8 bytes (int64)
  • Range: ±290 years
  • Precision: 1 nanosecond

Big Duration:

  • Size: 8 bytes (int64)
  • Range: ±292 billion years
  • Precision: 1 second
Benchmarks
Operation Standard Big Notes
Parse ~500ns ~500ns Similar performance
String ~200ns ~200ns Same formatting logic
JSON Marshal ~300ns ~300ns Encoding overhead
JSON Unmarshal ~800ns ~800ns Parsing + validation
Arithmetic ~5ns ~5ns Native int64 operations
Conversion ~10ns ~10ns Type casting

Benchmarks on AMD64, Go 1.21

When to Use Which

Use Standard Duration when:

  • Durations < 290 years
  • Need nanosecond precision
  • Working with standard library (time.Duration)
  • Short-term timers, timeouts, delays

Use Big Duration when:

  • Durations > 290 years
  • Astronomical calculations
  • Long-term scheduling (centuries, millennia)
  • Second precision is sufficient

Use Cases

Standard Duration

HTTP Timeouts

type ServerConfig struct {
    ReadTimeout  duration.Duration `json:"read_timeout"`
    WriteTimeout duration.Duration `json:"write_timeout"`
    IdleTimeout  duration.Duration `json:"idle_timeout"`
}

cfg := ServerConfig{
    ReadTimeout:  duration.Seconds(10),
    WriteTimeout: duration.Seconds(10),
    IdleTimeout:  duration.Minutes(2),
}

server := &http.Server{
    ReadTimeout:  cfg.ReadTimeout.Time(),
    WriteTimeout: cfg.WriteTimeout.Time(),
    IdleTimeout:  cfg.IdleTimeout.Time(),
}

Cache Expiration

type CacheConfig struct {
    TTL duration.Duration `yaml:"ttl"`
}

cfg := CacheConfig{
    TTL: duration.Hours(24),
}

cache.Set(key, value, cfg.TTL.Time())

Retry Backoff

backoff := duration.Seconds(1)
maxBackoff := duration.Minutes(5)

for i := 0; i < maxRetries; i++ {
    if err := doSomething(); err == nil {
        break
    }
    
    time.Sleep(backoff.Time())
    backoff = backoff * 2
    if backoff > maxBackoff {
        backoff = maxBackoff
    }
}
Big Duration

Astronomy

// Earth's orbital period
earthYear := durbig.Days(365.25)

// Solar system age (4.6 billion years)
solarSystemAge := durbig.Days(365.25 * 4_600_000_000)

fmt.Println(solarSystemAge.String())

Geological Time

// Age of dinosaur extinction (66 million years ago)
extinction := durbig.Days(365.25 * 66_000_000)

// Jurassic period duration (56 million years)
jurassic := durbig.Days(365.25 * 56_000_000)

Long-Term Scheduling

// Archive retention (1000 years)
retention := durbig.Days(365 * 1000)

// Next solar eclipse in 500 years
nextEclipse := durbig.Days(365 * 500)

Best Practices

1. Choose the Right Type
// ✅ Good: Use standard duration for typical cases
timeout := duration.Seconds(30)

// ✅ Good: Use big duration for very large durations
archiveAge := durbig.Days(10000)

// ❌ Bad: Using big duration unnecessarily
delay := durbig.Seconds(5)  // Overkill, use standard
2. Use Constructor Functions
// ✅ Good: Type-safe constructors
timeout := duration.Minutes(5)

// ❌ Bad: Manual conversion
timeout := duration.Duration(5 * 60 * time.Second)
3. Handle Parse Errors
// ✅ Good: Check errors
d, err := duration.Parse(userInput)
if err != nil {
    log.Printf("Invalid duration: %v", err)
    d = duration.Minutes(5)  // Fallback
}

// ❌ Bad: Ignoring errors
d, _ := duration.Parse(userInput)
4. Use Days Notation
// ✅ Good: Readable
retention := duration.Days(90)

// ❌ Less readable
retention := duration.Hours(24 * 90)
5. Truncate When Needed
// ✅ Good: Truncate for cleaner output
d := duration.Parse("2d3h15m30s")
fmt.Println(d.TruncateDays().String())  // "2d"

// Context-dependent: Keep precision if needed
precise := d.String()  // "2d3h15m30s"

Testing

Comprehensive testing documentation is available in TESTING.md.

Quick Test:

cd duration
go test -v -cover

cd big
go test -v -cover

Test Metrics:

  • Standard duration: 93.5% coverage, 150+ specs
  • Big duration: 91% coverage, 250+ specs
  • Ginkgo v2 + Gomega framework

Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass existing tests
  • Maintain or improve test coverage
  • Follow existing code style

Documentation

  • Update README.md for new features
  • Add examples for common use cases
  • Keep TESTING.md synchronized
  • Document all public APIs with GoDoc

Testing

  • Write tests for all new features
  • Test edge cases (overflow, underflow, invalid input)
  • Verify encoding/decoding works correctly
  • Include benchmarks for performance-critical code

Pull Requests

  • Provide clear description of changes
  • Reference related issues
  • Include test results
  • Update documentation

See CONTRIBUTING.md for detailed guidelines.


Future Enhancements

Potential improvements for future versions:

Standard Duration

  • More time units (weeks, months, years)
  • Duration arithmetic helpers (min, max, clamp)
  • Duration formatting templates
  • Localization support for parsing/formatting

Big Duration

  • Decimal precision (sub-second support)
  • Overflow detection and handling
  • More conversion helpers (to/from various types)
  • Performance optimizations for very large values

Both Packages

  • Interactive duration calculator
  • Visual duration comparison tools
  • More encoding formats (MessagePack, etc.)
  • Duration validation helpers

Suggestions and contributions are welcome via GitHub issues.


Go Standard Library
Encoding Libraries
Configuration
  • Viper - Configuration management
  • config - Configuration management
  • logger - Logging (used in examples)

License

MIT License - See LICENSE file for details.

Copyright (c) 2022 Nicolas JUHEL


Resources


This package is part of the golib project.

Documentation

Overview

Package duration provides an extended duration type with days support and multiple encoding formats.

This package wraps time.Duration and extends it with:

  • Days notation in parsing and formatting (e.g., "5d23h15m13s")
  • Multiple encoding support (JSON, YAML, TOML, CBOR, text)
  • Viper configuration integration
  • Arithmetic operations and helper functions
  • Truncation and rounding to various time units
  • PID controller-based range generation

The package is limited to time.Duration's range (±290 years). For larger durations, use the big sub-package.

Example usage:

import "github.com/nabbar/golib/duration"

// Parse duration with days
d, _ := duration.Parse("5d23h15m13s")
fmt.Println(d.String())  // Output: 5d23h15m13s

// Create durations
timeout := duration.Days(2) + duration.Hours(3)

// Convert to time.Duration
std := timeout.Time()

// Use in JSON
type Config struct {
    Timeout duration.Duration `json:"timeout"`
}

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultRateProportional float64 = 0.1
	DefaultRateIntegral     float64 = 0.01
	DefaultRateDerivative   float64 = 0.05
)

Functions

func ViperDecoderHook

func ViperDecoderHook() libmap.DecodeHookFuncType

ViperDecoderHook is a libmap.DecodeHookFuncType that is used to decode strings into libdur.Duration values. It takes a reflect.Type, a reflect.Type, and an interface{} as parameters, and returns an interface{} and an error. If the data type is not a string, it returns the data as is and a nil error. If the target type is not a libdur.Duration, it returns the data as is and a nil error. Otherwise, it formats/decodes/parses the data and returns the new value.

Types

type Duration

type Duration time.Duration

func Days

func Days(i int64) Duration

Days returns a Duration representing i days.

The returned Duration is a new Duration and does not modify the underlying time.Duration.

The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.

The duration is calculated by multiplying i by 24 hours (1 day).

func Hours

func Hours(i int64) Duration

Hours returns a Duration representing i hours.

The returned Duration is a new Duration and does not modify the underlying time.Duration.

The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.

func Minutes

func Minutes(i int64) Duration

Minutes returns a Duration representing i minutes.

The returned Duration is a new Duration and does not modify the underlying time.Duration.

The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.

func Parse

func Parse(s string) (Duration, error)

Parse parses a string representing a duration and returns a Duration object. It will return an error if the string is invalid.

The string must be in the format "XhYmZs" where X, Y, and Z are integers representing the number of hours, minutes, and seconds respectively. The letters "h", "m", and "s" are optional and can be omitted.

For example, "2h" represents 2 hours, "3m" represents 3 minutes, and "4s" represents 4 seconds.

The function is case insensitive.

func ParseByte

func ParseByte(p []byte) (Duration, error)

ParseByte parses a byte array representing a duration and returns a Duration object. It will return an error if the byte array is invalid.

The byte array must be in the format "XhYmZs" where X, Y, and Z are integers representing the number of hours, minutes, and seconds respectively. The letters "h", "m", and "s" are optional and can be omitted.

For example, "2h" represents 2 hours, "3m" represents 3 minutes, and "4s" represents 4 seconds.

The function is case insensitive.

func ParseDuration

func ParseDuration(d time.Duration) Duration

ParseDuration returns a Duration representing d time.Duration.

The returned Duration is a new Duration and does not modify the underlying time.Duration.

The function is a no-op and simply returns the input time.Duration as a Duration. It can be used to convert a time.Duration to a Duration without modifying the underlying time.Duration.

Example:

d := 5*time.Hour
dd := ParseDuration(d)
fmt.Println(dd) // 5h0m0s

func ParseFloat64 added in v1.17.0

func ParseFloat64(f float64) Duration

ParseFloat64 returns a Duration representing f seconds.

If f is larger than math.MaxInt64, ParseFloat64 returns a Duration representing math.MaxInt64 seconds. If f is smaller than -math.MaxInt64, ParseFloat64 returns a Duration representing -math.MaxInt64 seconds.

Otherwise, ParseFloat64 returns a Duration representing the closest integer to f seconds. The returned Duration is a new Duration and does not modify the underlying float64.

func ParseUint32 added in v1.19.0

func ParseUint32(i uint32) Duration

func Seconds

func Seconds(i int64) Duration

Seconds returns a Duration representing i seconds.

The returned Duration is a new Duration and does not modify the underlying time.Duration.

The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.

func (Duration) Days

func (d Duration) Days() int64

Days returns the number of days in the duration. The number of days is calculated by dividing the total number of hours by 24 and rounding down to the nearest integer. If the total number of hours is greater than the maximum value of int64, the maximum value of int64 is returned.

func (Duration) Float64 added in v1.17.0

func (d Duration) Float64() float64

Float64 returns the underlying int64 value of the duration as a float64.

This can be useful when working with libraries or functions that expect a float64 value, as it allows for easy conversion between the duration package and the required type.

Example:

d := libdur.ParseDuration("1h30m") f := d.Float64() fmt.Println(f) // Output: 5400.0

func (Duration) MarshalCBOR

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

MarshalCBOR returns the CBOR encoding of the duration.

The CBOR encoding is simply the CBOR encoding of the string representation of the duration.

Example:

d := duration.MustParse("1h2m3s") b, err := d.MarshalCBOR()

if err != nil {
    panic(err)
}

fmt.Println(string(b)) // Output: CBOR encoding of "1h2m3s"

func (Duration) MarshalJSON

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

MarshalJSON returns the JSON encoding of the duration.

The JSON encoding is simply the string representation of the duration wrapped in double quotes.

Example:

d := duration.MustParse("1h2m3s") b, err := d.MarshalJSON()

if err != nil {
    panic(err)
}

fmt.Println(string(b)) // Output: "1h2m3s"

func (Duration) MarshalTOML

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

func (Duration) MarshalText

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

MarshalText returns the text encoding of the duration.

The text encoding is simply the string representation of the duration.

Example:

d := duration.MustParse("1h2m3s") b, err := d.MarshalText()

if err != nil {
    panic(err)
}

fmt.Println(string(b)) // Output: "1h2m3s"

func (Duration) MarshalYAML

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

MarshalYAML returns the YAML encoding of the duration.

The YAML encoding is simply the string representation of the duration.

Example:

d := duration.MustParse("1h2m3s") y, err := d.MarshalYAML()

if err != nil {
    panic(err)
}

fmt.Println(y) // Output: "1h2m3s"

func (Duration) RangeCtxFrom added in v1.19.0

func (d Duration) RangeCtxFrom(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration

RangeCtxFrom generates a list of durations from dur to d, spaced according to the given PID controller parameters.

The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.

If the last element of the list is less than the start duration, the start duration is added to the end of the list.

The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate

The context is used to cancel the range generation if the context is canceled before the range is fully generated. If the context is canceled before the range is fully generated, the function will return an empty list.

func (Duration) RangeCtxTo added in v1.19.0

func (d Duration) RangeCtxTo(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration

RangeCtxTo generates a list of durations from d to dur, spaced according to the given PID controller parameters.

The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.

If the last element of the list is less than the end duration, the end duration is added to the end of the list.

The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate

The context is used to cancel the range generation if the context is canceled before the range is fully generated.

func (Duration) RangeDefFrom added in v1.17.0

func (d Duration) RangeDefFrom(dur Duration) []Duration

RangeDefFrom generates a list of durations from dur to d, spaced according to the default PID controller parameters.

The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.

If the last element of the list is less than the start duration, the start duration is added to the end of the list.

func (Duration) RangeDefTo added in v1.17.0

func (d Duration) RangeDefTo(dur Duration) []Duration

RangeDefTo generates a list of durations from d to dur, spaced according to the default PID controller parameters.

The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.

If the last element of the list is less than the end duration, the end duration is added to the end of the list.

func (Duration) RangeFrom added in v1.17.0

func (d Duration) RangeFrom(dur Duration, rateP, rateI, rateD float64) []Duration

RangeFrom generates a list of durations from dur to d, spaced according to the given PID controller parameters.

The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.

If the last element of the list is less than the start duration, the start duration is added to the end of the list.

The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate

The context is used to cancel the range generation if the context is canceled before the range is fully generated. If the context is canceled before the range is fully generated, the function will return an empty list.

func (Duration) RangeTo added in v1.17.0

func (d Duration) RangeTo(dur Duration, rateP, rateI, rateD float64) []Duration

RangeTo generates a list of durations from d to dur, spaced according to the given PID controller parameters.

The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.

If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.

If the last element of the list is less than the end duration, the end duration is added to the end of the list.

The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate

If the context is canceled before the range is fully generated, the function will return an empty list.

func (Duration) String

func (d Duration) String() string

String returns a string representation of the duration. The string is in the format "NdNhNmNs" where N is a number. The days are omitted if n is 0 or negative. The hours, minutes, and seconds are omitted if they are 0.

Example:

d := libdur.ParseDuration("1d2h3m4s") fmt.Println(d.String()) // Output: 1d2h3m4s

func (Duration) Time

func (d Duration) Time() time.Duration

Time returns a time.Duration representation of the duration. It is a simple wrapper around the conversion of the underlying int64 value to a time.Duration.

Time is useful when working with the time package, as it allows for easy conversion between the duration package and the time package.

Example:

d := libdur.ParseDuration("1h30m") td := d.Time() fmt.Println(td) // Output: 1h30m0s

func (Duration) TruncateDays added in v1.15.3

func (d Duration) TruncateDays() Duration

TruncateDays returns the result of rounding d toward zero to a multiple of a day. If d is an exact multiple of a day, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a day. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a day, it rounds up to the next multiple of a day. For example, TruncateDays(ParseDuration("1.5d")) returns ParseDuration("2d").

func (Duration) TruncateHours added in v1.15.3

func (d Duration) TruncateHours() Duration

TruncateHours returns the result of rounding d toward zero to a multiple of an hour. If d is an exact multiple of an hour, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of an hour. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of an hour, it rounds up to the next multiple of an hour. For example, TruncateHours(ParseDuration("1.5h")) returns ParseDuration("2h").

func (Duration) TruncateMicroseconds added in v1.15.3

func (d Duration) TruncateMicroseconds() Duration

TruncateMicroseconds returns the result of rounding d toward zero to a multiple of a microsecond. If d is an exact multiple of a microsecond, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a microsecond. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a microsecond, it rounds up to the next multiple of a microsecond). For example, TruncateMicroseconds(ParseDuration("1.5µs")) returns ParseDuration("2µs").

func (Duration) TruncateMilliseconds added in v1.15.3

func (d Duration) TruncateMilliseconds() Duration

TruncateMilliseconds returns the result of rounding d toward zero to a multiple of a millisecond. If d is an exact multiple of a millisecond, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a millisecond. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a millisecond, it rounds up to the next multiple of a millisecond. For example, TruncateMilliseconds(ParseDuration("1.5ms")) returns ParseDuration("2ms").

func (Duration) TruncateMinutes added in v1.15.3

func (d Duration) TruncateMinutes() Duration

TruncateMinutes returns the result of rounding d toward zero to a multiple of a minute. If d is an exact multiple of a minute, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a minute. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a minute, it rounds up to the next multiple of a minute. For example, TruncateMinutes(ParseDuration("1.5m")) returns ParseDuration("2m").

func (Duration) TruncateSeconds added in v1.15.3

func (d Duration) TruncateSeconds() Duration

TruncateSeconds returns the result of rounding d toward zero to a multiple of a second. If d is an exact multiple of a second, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a second. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a second, it rounds up to the next multiple of a second. For example, TruncateSeconds(ParseDuration("1.5s")) returns ParseDuration("2s").

func (*Duration) UnmarshalCBOR

func (d *Duration) UnmarshalCBOR(bytes []byte) error

UnmarshalCBOR parses the CBOR-encoded duration and stores the result in the receiver.

The CBOR encoding is expected to be the CBOR encoding of the string representation of the duration.

Example:

d := &duration.Duration{} b := []byte{CBOR encoding of "1h2m3s"}

if err := d.UnmarshalCBOR(b); err != nil {
    panic(err)
}

fmt.Println(d.String()) // Output: "1h2m3s"

func (*Duration) UnmarshalJSON

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

UnmarshalJSON parses the JSON-encoded duration and stores the result in the receiver.

The JSON encoding is expected to be a string representation of the duration wrapped in double quotes.

Example:

b := []byte(`"1h2m3s"`) d := &duration.Duration{}

if err := d.UnmarshalJSON(b); err != nil {
    panic(err)
}

fmt.Println(d.String()) // Output: "1h2m3s"

func (*Duration) UnmarshalTOML

func (d *Duration) UnmarshalTOML(i interface{}) error

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(bytes []byte) error

UnmarshalText parses the text-encoded duration and stores the result in the receiver.

The text encoding is expected to be a string representation of the duration.

Example:

d := &duration.Duration{} b := []byte("1h2m3s")

if err := d.UnmarshalText(b); err != nil {
    panic(err)
}

fmt.Println(d.String()) // Output: "1h2m3s"

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML parses the YAML-encoded duration and stores the result in the receiver.

The YAML encoding is expected to be a string representation of the duration.

Example:

y := &yaml.Node{Value: "1h2m3s"} d := &duration.Duration{}

if err := d.UnmarshalYAML(y); err != nil {
    panic(err)
}

fmt.Println(d.String()) // Output: "1h2m3s"

Directories

Path Synopsis
Package big provides duration handling for very large time intervals beyond time.Duration limits.
Package big provides duration handling for very large time intervals beyond time.Duration limits.

Jump to

Keyboard shortcuts

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