Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Last active July 7, 2023 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwilczynski/5052c37a17ea683fdf199160b0d8c9a9 to your computer and use it in GitHub Desktop.
Save kwilczynski/5052c37a17ea683fdf199160b0d8c9a9 to your computer and use it in GitHub Desktop.
Parse time duration as string - either assume seconds or parse string as rich format e.g., 5m 30s, etc.
package main
import (
"fmt"
"strconv"
"time"
)
func parseExpiry(s string) (time.Duration, error) {
var t time.Duration
n, err := strconv.ParseInt(s, 10, 64)
if err == nil {
t = time.Duration(n) * time.Second
} else {
t, err = time.ParseDuration(s)
}
if err != nil {
return 0, err
}
if t < 0 {
t = -t
}
return t, nil
}
func main() {
// Assume seconds by default.
fmt.Println(parseExpiry("300"))
// Rich string parsing.
fmt.Println(parseExpiry("5m"))
// Handle negative values.
fmt.Println(parseExpiry("-2"))
// Return error on parsing failure.
fmt.Println(parseExpiry("abc"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment