utils/time.go

70 lines
1.4 KiB
Go

package utils
import (
"fmt"
"strconv"
"strings"
"time"
)
func StringTimestamp2GoTime(s string) (ts time.Time) {
secs, err := strconv.ParseInt(s, 10, 64)
if err == nil {
ts = time.Unix(secs, 0)
}
return
}
func StringSeconds2GoDuration(s string) (secs time.Duration) {
if len(s) > 0 {
if s[len(s)-1] != 's' {
s += "s"
}
secs, _ = time.ParseDuration(s)
}
return
}
// Convert the spec string to a number of seconds.
// spec is a number, optionally followed by a time unit among 's'(seconds),
// 'm'(minutes), 'h'(hours), and 'd'(days)
// If the time unit is omitted, defaultUnit is used.
// Empty spec returns 0 seconds.
func ParseTimeInterval(spec string, defaultUnit byte) (interval int64, err error) {
var u byte
var intVal int
spec = strings.TrimSpace(spec)
if len(spec) == 0 {
//err = errors.New(iface.ErrEmptyValue)
return
}
spec = strings.ToLower(spec)
u = spec[len(spec)-1]
if u >= '0' && u <= '9' {
u = 'm'
} else {
spec = spec[0 : len(spec)-1]
}
if intVal, err = strconv.Atoi(spec); err != nil {
return
// } else if intVal <= 0 {
// err = errors.New(iface.ErrMustBePositive)
// return
}
switch u {
case 's':
interval = int64(intVal)
case 'm':
interval = int64(intVal) * 60
case 'h':
interval = int64(intVal) * 3600
case 'd':
interval = int64(intVal) * 86400
default:
err = fmt.Errorf("invalid time unit %c", u)
}
return
}