human_duration.go 540 B

1234567891011121314151617181920212223242526272829
  1. package utils
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. )
  7. func ParseDuration(d string) (time.Duration, error) {
  8. d = strings.TrimSpace(d)
  9. dr, err := time.ParseDuration(d)
  10. if err == nil {
  11. return dr, nil
  12. }
  13. if strings.Contains(d, "d") {
  14. index := strings.Index(d, "d")
  15. hour, _ := strconv.Atoi(d[:index])
  16. dr = time.Hour * 24 * time.Duration(hour)
  17. ndr, err := time.ParseDuration(d[index+1:])
  18. if err != nil {
  19. return dr, nil
  20. }
  21. return dr + ndr, nil
  22. }
  23. dv, err := strconv.ParseInt(d, 10, 64)
  24. return time.Duration(dv), err
  25. }