feat(tyme/dur): add dur package as separate module

This commit is contained in:
2022-10-30 03:31:46 +00:00
parent 572d532b77
commit 5d31aa6743
13 changed files with 940 additions and 0 deletions

33
dur/parse.go Normal file
View File

@@ -0,0 +1,33 @@
package dur
import (
"fmt"
"time"
)
const floatSecond = float64(time.Second)
// Parse parses given interface to a Duration.
//
// If the interface is a string, it will be parsed using time.Parse. If
// the interface is a int or float64, it will be parsed as a number of seconds.
func Parse(x interface{}) (Duration, error) {
var d Duration
switch value := x.(type) {
case string:
td, err := time.ParseDuration(value)
if err != nil {
return 0, err
}
d = Duration(td)
case float64:
d = Duration(time.Duration(value * floatSecond))
case int:
d = Duration(time.Duration(value) * time.Second)
default:
return 0, fmt.Errorf("time: invalid duration %+v", x)
}
return d, nil
}