durafmt

package module
Version: v0.0.0-...-5c1018a Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2021 License: MIT Imports: 6 Imported by: 202

README

durafmt

Build Status Go Report Card codecov GoDoc Open Source Helpers

durafmt is a tiny Go library that formats time.Duration strings (and types) into a human readable format.

go get github.com/hako/durafmt

Why

If you've worked with time.Duration in Go, you most likely have come across this:

53m28.587093086s // :)

The above seems very easy to read, unless your duration looks like this:

354h22m3.24s // :S

Usage

durafmt.ParseString()
package main

import (
	"fmt"
	"github.com/hako/durafmt"
)

func main() {
	duration, err := durafmt.ParseString("354h22m3.24s")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
	// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
}
durafmt.ParseStringShort()

Version of durafmt.ParseString() that only returns the first part of the duration string.

package main

import (
	"fmt"
	"github.com/hako/durafmt"
)

func main() {
	duration, err := durafmt.ParseStringShort("354h22m3.24s")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(duration) // 2 weeks
	// duration.String() // String short representation. "2 weeks"
}
durafmt.Parse()
package main

import (
	"fmt"
	"time"
	"github.com/hako/durafmt"
)

func main() {
	timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
	duration := durafmt.Parse(timeduration).String()
	fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
}
LimitFirstN()

Like durafmt.ParseStringShort() but for limiting the first N parts of the duration string.

package main

import (
	"fmt"
	"time"
	"github.com/hako/durafmt"
)

func main() {
	timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
	duration := durafmt.Parse(timeduration).LimitFirstN(2) // // limit first two parts.
	fmt.Println(duration) // 2 weeks 18 hours
}
Custom Units

Like durafmt.Units{} and durafmt.Durafmt.Format(units) to stringify duration with custom units.

package main

import (
	"fmt"
	"time"
	"github.com/hako/durafmt"
)

func main() {
	timeduration := (354 * time.Hour) + (22 * time.Minute) + (1 * time.Second) + (100*time.Microsecond)
	duration := durafmt.Parse(timeduration)
	// units in portuguese
	units, err := durafmt.DefaultUnitsCoder.Decode("ano,semana,dia,hora,minuto,segundo,milissegundo,microssegundo")
	if err != nil {
		panic(err)
	}
	fmt.Println(duration.Format(units)) // 2 semanas 18 horas 22 minutos 1 segundo 100 microssegundos

    // custom plural (singular:plural)
	units, err = durafmt.DefaultUnitsCoder.Decode("ano,semana:SEMANAS,dia,hora,minuto,segundo,milissegundo,microssegundo")
	if err != nil {
		panic(err)
	}
	fmt.Println(duration.Format(units)) // 2 SEMANAS 18 horas 22 minutos 1 segundo 100 microssegundos
}

Contributing

Contributions are welcome! Fork this repo, add your changes and submit a PR.

If you would like to fix a bug, add a feature or provide feedback you can do so in the issues section.

durafmt is tested against golangci-lint and you can run tests with go test.

When contributing, running go test; go vet; golint or golangci-lint is recommended.

License

MIT

Documentation

Overview

Package durafmt formats time.Duration into a human readable format.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultUnitsCoder = UnitsCoder{":", ","}

DefaultUnitsCoder default units coder using `":"` as PluralSep and `","` as UnitsSep

Functions

This section is empty.

Types

type Durafmt

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

Durafmt holds the parsed duration and the original input duration.

func Parse

func Parse(dinput time.Duration) *Durafmt

Parse creates a new *Durafmt struct, returns error if input is invalid.

Example
timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
duration := Parse(timeduration).String()
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
Output:

func ParseShort

func ParseShort(dinput time.Duration) *Durafmt

ParseShort creates a new *Durafmt struct, short form, returns error if input is invalid. It's shortcut for `Parse(dur).LimitFirstN(1)`

Example

Version of durafmt.Parse() that only returns the first part of the duration string.

timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
duration := ParseShort(timeduration).String()
fmt.Println(duration) // 2 weeks
Output:

func ParseString

func ParseString(input string) (*Durafmt, error)

ParseString creates a new *Durafmt struct from a string. returns an error if input is invalid.

Example
duration, err := ParseString("354h22m3.24s")
if err != nil {
	fmt.Println(err)
}
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
Output:

Example (Sequence)
for hours := 1.0; hours < 12.0; hours++ {
	hour := fmt.Sprintf("%fh", math.Pow(2, hours))
	duration, err := ParseString(hour)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(duration) // 2 hours, 4 hours, ...
}
Output:

func ParseStringShort

func ParseStringShort(input string) (*Durafmt, error)

ParseStringShort creates a new *Durafmt struct from a string, short form returns an error if input is invalid. It's shortcut for `ParseString(durStr)` and then calling `LimitFirstN(1)`

Example

Version of durafmt.ParseString() that only returns the first part of the duration string.

duration, err := ParseStringShort("354h22m3.24s")
if err != nil {
	fmt.Println(err)
}
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
Output:

func (*Durafmt) Duration

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

func (*Durafmt) Format

func (d *Durafmt) Format(units Units) string

Format parses d *Durafmt into a human readable duration with units.

Example
timeduration := (354 * time.Hour) + (22 * time.Minute) + (1 * time.Second) + (100 * time.Microsecond)
duration := Parse(timeduration)
// units in portuguese
units, err := DefaultUnitsCoder.Decode("ano,semana,dia,hora,minuto,segundo,milissegundo,microssegundo")
if err != nil {
	panic(err)
}
fmt.Println(duration.Format(units)) // 2 semanas 18 horas 22 minutos 1 segundo 100 microssegundos

// custom plural (singular:plural)
units, err = DefaultUnitsCoder.Decode("ano,semana:SEMANAS,dia,hora,minuto,segundo,milissegundo,microssegundo")
if err != nil {
	panic(err)
}
fmt.Println(duration.Format(units)) // 2 SEMANAS 18 horas 22 minutos 1 segundo 100 microssegundos
Output:

func (*Durafmt) InternationalString

func (d *Durafmt) InternationalString() string

func (*Durafmt) LimitFirstN

func (d *Durafmt) LimitFirstN(n int) *Durafmt

LimitFirstN sets the output format, outputing only first N elements. n == 0 means no limit.

Example
duration, err := ParseString("354h22m3.24s")
if err != nil {
	fmt.Println(err)
}
duration = duration.LimitFirstN(2)
fmt.Println(duration) // 2 weeks 18 hours
// duration.String() // String representation. "2 weeks 18 hours"
Output:

func (*Durafmt) LimitToUnit

func (d *Durafmt) LimitToUnit(unit string) *Durafmt

LimitToUnit sets the output format, you will not have unit bigger than the UNIT specified. UNIT = "" means no restriction.

Example
duration, err := ParseString("354h22m3.24s")
if err != nil {
	fmt.Println(err)
}
duration = duration.LimitToUnit("days")
fmt.Println(duration) // 14 days 18 hours 22 minutes 3 seconds
// duration.String() // String representation. "14 days 18 hours 22 minutes 3 seconds"
Output:

func (*Durafmt) String

func (d *Durafmt) String() string

String parses d *Durafmt into a human readable duration with default units.

type Unit

type Unit struct {
	Singular, Plural string
}

Unit the pair of singular and plural units

type Units

type Units struct {
	Year, Week, Day, Hour, Minute,
	Second, Millisecond, Microsecond Unit
}

Units duration units

func (Units) Units

func (u Units) Units() []Unit

Units return a slice of units

type UnitsCoder

type UnitsCoder struct {
	// PluralSep char to sep singular and plural pair.
	// Example with char `":"`: `"year:year"` (english) or `"mês:meses"` (portuguese)
	PluralSep,

	UnitsSep string
}

UnitsCoder the units encoder and decoder

func (UnitsCoder) Decode

func (coder UnitsCoder) Decode(s string) (units Units, err error)

Decode decodes input string to Units. The input must follow the following formats: - Unit format (singular and plural pair)

- must singular (the plural receives 's' character as suffix)
- singular and plural: separated by `PluralSep` char
	Example with char `":"`: `"year:year"` (english) or `"mês:meses"` (portuguese)

- Units format (pairs of Year, Week, Day, Hour, Minute,

Second, Millisecond and Microsecond units) separated by `UnitsSep` char
- Examples with `UnitsCoder{PluralSep: ":", UnitsSep = ","}`
	- must singular units: `"year,week,day,hour,minute,second,millisecond,microsecond"`
	- mixed units: `"year,week:weeks,day,hour,minute:minutes,second,millisecond,microsecond"`
	- singular and plural pair units: `"year:wers,week:weeks,day:days,hour:hours,minute:minutes,second:seconds,millisecond:millliseconds,microsecond:microsseconds"`

func (UnitsCoder) Encode

func (coder UnitsCoder) Encode(units Units) string

Encode encodes input Units to string Examples with `UnitsCoder{PluralSep: ":", UnitsSep = ","}`

- singular and plural pair units: `"year:wers,week:weeks,day:days,hour:hours,minute:minutes,second:seconds,millisecond:millliseconds,microsecond:microsseconds"`

Source Files

Jump to

Keyboard shortcuts

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