Documentation
¶
Overview ¶
Package duration provides an extended time.Duration type that supports parsing and formatting with "days" (d) as a unit. It also integrates seamlessly with various encoding formats (JSON, YAML, TOML, CBOR) and offers advanced features like PID-controlled range generation and precise truncation.
Overview ¶
The standard Go time.Duration is limited to hours as its largest parsed unit. This package solves that by introducing a `Duration` type that behaves like time.Duration but adds support for days in string representations (e.g., "5d12h"). It also provides a robust set of helpers for conversion, comparison, and arithmetic operations.
Features ¶
- **Extended Parsing:** Support for "d" (days) in duration strings (e.g., "1d2h30m"). - **Serialization:** Built-in support for Marshaling/Unmarshaling to/from JSON, YAML, TOML, CBOR, and Text. - **Helper Functions:** Easy constructors like Days(n), Hours(n), Minutes(n), etc. - **Truncation:** methods to truncate durations to days, hours, minutes, seconds, etc. - **Range Generation:** Generate sequences of durations using a PID controller for smooth transitions (useful for backoff strategies). - **Configuration Integration:** Includes a hook for Viper/Mapstructure decoding. - **Big Duration Support:** A sub-package `big` handles durations exceeding the standard int64 limit (±290 years).
Architecture & Data Flow
The core of the package is the `Duration` type, which is a simple type alias for `int64` (same as `time.Duration`). This ensures zero-cost conversion to standard `time.Duration` while allowing method attachment.
+----------------+ +---------------------+ +-------------------+
| Input String | ----> | Parse() / Unmarshal | ---> | Duration (int64) |
| "1d2h" | +---------------------+ | |
+----------------+ +---------+---------+
|
v
+----------------+ +---------------------+ +---------+---------+
| Output String | <---- | String() / Marshal | <----| Operations |
| "1d2h0m0s" | +---------------------+ | - Truncate |
+----------------+ | - Range |
| - Convert |
+-------------------+
Quick Start
package main
import (
"fmt"
"time"
"github.com/nabbar/golib/duration"
)
func main() {
// 1. Parsing a duration string with days
d, err := duration.Parse("2d4h")
if err != nil {
panic(err)
}
fmt.Println("Parsed:", d) // Output: 2d4h0m0s
// 2. Creating a duration from integers
d2 := duration.Days(1) + duration.Hours(12)
fmt.Println("Constructed:", d2) // Output: 1d12h0m0s
// 3. Converting to standard time.Duration
stdDuration := d.Time()
fmt.Printf("Standard: %v\n", stdDuration) // Output: 52h0m0s
// 4. Truncating
fmt.Println("Truncated to days:", d.TruncateDays()) // Output: 2d
// 5. Checking units
if d.IsDays() {
fmt.Println("Duration is at least one day")
}
}
Use Cases ¶
Configuration Files: Allow users to specify long timeouts or intervals in a human-readable format in config files (JSON, YAML, etc.). Example: `timeout: "7d"` is clearer than `timeout: "168h"`.
Exponential Backoff / Retries: Use `RangeTo` or `RangeCtxTo` to generate a sequence of durations for retry attempts that increase over time using a PID controller logic.
API Responses: Return duration fields in JSON APIs that are easy for humans to read and for clients to parse.
Scheduling: Calculate precise schedules involving days, where standard `time.Duration` logic might be cumbersome due to the lack of a 'day' unit.
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"`
}
Example (Configuration) ¶
Example_configuration demonstrates how to use duration in a configuration struct with JSON.
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/nabbar/golib/duration"
)
func main() {
// Imagine this JSON is from a config file.
configJSON := `{"timeout": "2d12h"}`
var config struct {
Timeout duration.Duration `json:"timeout"`
}
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
log.Fatalf("Failed to unmarshal config: %v", err)
}
fmt.Printf("Timeout is: %s\n", config.Timeout)
fmt.Printf("In hours: %d hours", config.Timeout.Hours())
}
Output: Timeout is: 2d12h0m0s In hours: 60 hours
Example (RetryStrategy) ¶
Example_retryStrategy demonstrates generating a series of durations for a retry mechanism.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
start := duration.Seconds(1)
end := duration.Minutes(1)
// Generate a backoff sequence.
// Note: The PID controller parameters here are for demonstration.
backoffSequence := start.RangeTo(end, 0.5, 0.1, 0.1)
fmt.Println("Retry intervals:")
for i, d := range backoffSequence {
fmt.Printf("Attempt %d: wait %s\n", i+1, d.String())
}
}
Output:
Index ¶
- Variables
- func ViperDecoderHook() libmap.DecodeHookFuncType
- type Duration
- func Days(i int64) Duration
- func Hours(i int64) Duration
- func Microseconds(i int64) Duration
- func Milliseconds(i int64) Duration
- func Minutes(i int64) Duration
- func Nanoseconds(i int64) Duration
- func Parse(s string) (Duration, error)
- func ParseByte(p []byte) (Duration, error)
- func ParseDuration(d time.Duration) Duration
- func ParseFloat64(f float64) Duration
- func ParseUint32(i uint32) Duration
- func Seconds(i int64) Duration
- func (d Duration) Days() int64
- func (d Duration) Duration() time.Duration
- func (d Duration) Float64() float64
- func (d Duration) Hours() int64
- func (d Duration) Int64() int64
- func (d Duration) IsDays() bool
- func (d Duration) IsHours() bool
- func (d Duration) IsMicroseconds() bool
- func (d Duration) IsMilliseconds() bool
- func (d Duration) IsMinutes() bool
- func (d Duration) IsNanoseconds() bool
- func (d Duration) IsSeconds() bool
- func (d Duration) MarshalCBOR() ([]byte, error)
- func (d Duration) MarshalJSON() ([]byte, error)
- func (d Duration) MarshalTOML() ([]byte, error)
- func (d Duration) MarshalText() ([]byte, error)
- func (d Duration) MarshalYAML() (interface{}, error)
- func (d Duration) Microseconds() int64
- func (d Duration) Milliseconds() int64
- func (d Duration) Minutes() int64
- func (d Duration) Nanoseconds() int64
- func (d Duration) RangeCtxFrom(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeCtxTo(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeDefFrom(dur Duration) []Duration
- func (d Duration) RangeDefTo(dur Duration) []Duration
- func (d Duration) RangeFrom(dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeTo(dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) Seconds() int64
- func (d Duration) String() string
- func (d Duration) Time() time.Duration
- func (d Duration) TruncateDays() Duration
- func (d Duration) TruncateHours() Duration
- func (d Duration) TruncateMicroseconds() Duration
- func (d Duration) TruncateMilliseconds() Duration
- func (d Duration) TruncateMinutes() Duration
- func (d Duration) TruncateSeconds() Duration
- func (d Duration) Uint64() uint64
- func (d *Duration) UnmarshalCBOR(bytes []byte) error
- func (d *Duration) UnmarshalJSON(bytes []byte) error
- func (d *Duration) UnmarshalTOML(i interface{}) error
- func (d *Duration) UnmarshalText(bytes []byte) error
- func (d *Duration) UnmarshalYAML(value *yaml.Node) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultRateDerivative float64 = 0.05
DefaultRateDerivative is the default derivative rate for the PID controller used in range generation.
var DefaultRateIntegral float64 = 0.01
DefaultRateIntegral is the default integral rate for the PID controller used in range generation.
var DefaultRateProportional float64 = 0.1
DefaultRateProportional is the default proportional rate for the PID controller used in range generation.
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 ¶
func Days ¶
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).
Example ¶
ExampleDays demonstrates creating a duration using the Days helper function.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
// Create a duration of 2 days.
d := duration.Days(2)
fmt.Println(d)
}
Output: 2d
func Hours ¶
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.
Example ¶
ExampleHours demonstrates creating a duration using the Hours helper function.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
// Create a duration of 36 hours.
d := duration.Hours(36)
fmt.Println(d)
}
Output: 1d12h0m0s
func Microseconds ¶ added in v1.21.0
Microseconds returns a Duration representing i microseconds.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
func Milliseconds ¶ added in v1.21.0
Milliseconds returns a Duration representing i milliseconds.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
func Minutes ¶
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 Nanoseconds ¶ added in v1.21.0
Nanoseconds returns a Duration representing i nanoseconds.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
func Parse ¶
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.
Example ¶
ExampleParse demonstrates how to parse a duration string, including days.
package main
import (
"fmt"
"log"
"github.com/nabbar/golib/duration"
)
func main() {
// Parsing a string with days, hours, minutes, and seconds.
d, err := duration.Parse("3d6h15m30s")
if err != nil {
log.Fatalf("Failed to parse duration: %v", err)
}
fmt.Println(d)
}
Output: 3d6h15m30s
func ParseByte ¶
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 ¶
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
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
ParseUint32 returns a Duration representing i nanoseconds. Since Duration is an int64 representing nanoseconds, a uint32 value will always fit within the Duration type without overflow.
func Seconds ¶
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 ¶
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) Duration ¶ added in v1.21.0
Duration returns the time.Duration value. It is equivalent to d.Time().
func (Duration) Float64 ¶ added in v1.17.0
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) Hours ¶ added in v1.21.0
Hours returns the number of hours in the duration. It calculates the total hours from the underlying time.Duration, rounds down to the nearest integer, and converts it to int64. This provides the total duration expressed in full hours.
func (Duration) Int64 ¶ added in v1.21.0
Int64 returns the duration as a signed 64-bit integer. It simply casts the underlying Duration (which is int64) to int64.
func (Duration) IsDays ¶ added in v1.21.0
IsDays checks if the duration is greater than or equal to one day. It returns true if the duration is at least 24 hours.
func (Duration) IsHours ¶ added in v1.21.0
IsHours checks if the duration is greater than or equal to one hour. It returns true if the duration is at least 60 minutes.
func (Duration) IsMicroseconds ¶ added in v1.21.0
IsMicroseconds checks if the duration is greater than or equal to one microsecond. It returns true if the duration is at least 1000 nanoseconds.
func (Duration) IsMilliseconds ¶ added in v1.21.0
IsMilliseconds checks if the duration is greater than or equal to one millisecond. It returns true if the duration is at least 1000 microseconds.
func (Duration) IsMinutes ¶ added in v1.21.0
IsMinutes checks if the duration is greater than or equal to one minute. It returns true if the duration is at least 60 seconds.
Example ¶
ExampleDuration_IsMinutes checks if a duration is at least one minute long.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
d1 := duration.Seconds(90)
d2 := duration.Seconds(30)
fmt.Printf("90s is at least a minute: %t\n", d1.IsMinutes())
fmt.Printf("30s is at least a minute: %t\n", d2.IsMinutes())
}
Output: 90s is at least a minute: true 30s is at least a minute: false
func (Duration) IsNanoseconds ¶ added in v1.21.0
IsNanoseconds checks if the duration is greater than or equal to one nanosecond. This is effectively checking if the duration is non-zero (assuming positive duration), as 1ns is the smallest unit.
func (Duration) IsSeconds ¶ added in v1.21.0
IsSeconds checks if the duration is greater than or equal to one second. It returns true if the duration is at least 1000 milliseconds.
func (Duration) MarshalCBOR ¶
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.Parse("1h2m3s") b, err := d.MarshalCBOR()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: CBOR encoding of "1h2m3s"
func (Duration) MarshalJSON ¶
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.Parse("1h2m3s") b, err := d.MarshalJSON()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: "1h2m3s"
func (Duration) MarshalTOML ¶
MarshalTOML returns the TOML encoding of the duration. It returns the JSON encoding of the string representation of the duration.
func (Duration) MarshalText ¶
MarshalText returns the text encoding of the duration.
The text encoding is simply the string representation of the duration.
Example:
d, _ := duration.Parse("1h2m3s") b, err := d.MarshalText()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: "1h2m3s"
func (Duration) MarshalYAML ¶
MarshalYAML returns the YAML encoding of the duration.
The YAML encoding is simply the string representation of the duration.
Example:
d, _ := duration.Parse("1h2m3s") y, err := d.MarshalYAML()
if err != nil {
panic(err)
}
fmt.Println(y) // Output: "1h2m3s"
func (Duration) Microseconds ¶ added in v1.21.0
Microseconds returns the duration as an integer microsecond count. It delegates to the underlying time.Duration.Microseconds() method.
func (Duration) Milliseconds ¶ added in v1.21.0
Milliseconds returns the duration as an integer millisecond count. It delegates to the underlying time.Duration.Milliseconds() method.
func (Duration) Minutes ¶ added in v1.21.0
Minutes returns the number of minutes in the duration. It calculates the total minutes from the underlying time.Duration, rounds down to the nearest integer, and converts it to int64. This provides the total duration expressed in full minutes.
func (Duration) Nanoseconds ¶ added in v1.21.0
Nanoseconds returns the duration as an integer nanosecond count. It delegates to the underlying time.Duration.Nanoseconds() method.
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 slice of durations from 'dur' up to the receiver 'd'. It is the reverse of RangeCtxTo, using the same PID-controlled spacing logic.
The context 'ctx' can be used to cancel the generation process. The 'rateP', 'rateI', and 'rateD' parameters configure the PID controller.
The resulting slice is guaranteed to start with 'dur' and end with 'd'.
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 slice of durations from the receiver 'd' to the 'dur' parameter. The spacing between durations is determined by a PID controller, allowing for non-linear intervals. This is useful for scenarios like exponential backoff or other adaptive timing strategies.
The context 'ctx' can be used to cancel the generation process. The 'rateP', 'rateI', and 'rateD' parameters configure the Proportional, Integral, and Derivative components of the PID controller, respectively.
The resulting slice is guaranteed to start with 'd' and end with 'dur'.
func (Duration) RangeDefFrom ¶ added in v1.17.0
RangeDefFrom is a convenience wrapper for RangeFrom that uses the default PID controller rates. It generates a slice of durations from 'dur' to the receiver 'd'.
func (Duration) RangeDefTo ¶ added in v1.17.0
RangeDefTo is a convenience wrapper for RangeTo that uses the default PID controller rates (DefaultRateProportional, DefaultRateIntegral, DefaultRateDerivative). It generates a slice of durations from the receiver 'd' to 'dur'.
func (Duration) RangeFrom ¶ added in v1.17.0
RangeFrom is a convenience wrapper for RangeCtxFrom that uses a background context with a 5-second timeout. It generates a slice of durations from 'dur' to the receiver 'd' using the specified PID controller rates.
func (Duration) RangeTo ¶ added in v1.17.0
RangeTo is a convenience wrapper for RangeCtxTo that uses a background context with a 5-second timeout. It generates a slice of durations from the receiver 'd' to 'dur' using the specified PID controller rates.
func (Duration) Seconds ¶ added in v1.21.0
Seconds returns the number of seconds in the duration. It calculates the total seconds from the underlying time.Duration, rounds down to the nearest integer, and converts it to int64. This provides the total duration expressed in full seconds.
func (Duration) 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 ¶
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
Example ¶
ExampleDuration_Time shows how to convert a custom Duration back to a standard time.Duration.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
d := duration.Days(1) + duration.Hours(12)
stdDur := d.Time()
fmt.Printf("Standard time.Duration: %v", stdDur)
}
Output: Standard time.Duration: 36h0m0s
func (Duration) TruncateDays ¶ added in v1.15.3
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").
Example ¶
ExampleDuration_TruncateDays demonstrates truncating a duration to the nearest whole day.
package main
import (
"fmt"
"github.com/nabbar/golib/duration"
)
func main() {
d, _ := duration.Parse("3d18h")
trunc := d.TruncateDays()
fmt.Println(trunc)
}
Output: 3d
func (Duration) TruncateHours ¶ added in v1.15.3
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
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
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
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
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) Uint64 ¶ added in v1.21.0
Uint64 returns the duration as an unsigned 64-bit integer. If the duration is negative, it returns the absolute value cast to uint64. Otherwise, it returns the duration cast to uint64.
func (*Duration) UnmarshalCBOR ¶
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 ¶
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 ¶
UnmarshalTOML parses the TOML-encoded duration and stores the result in the receiver.
The TOML encoding is expected to be a string representation of the duration.
func (*Duration) UnmarshalText ¶
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 ¶
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"
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package big provides a custom duration type that extends the standard `time.Duration` to support much larger time scales, up to billions of years.
|
Package big provides a custom duration type that extends the standard `time.Duration` to support much larger time scales, up to billions of years. |