Last active
July 7, 2023 14:49
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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