2020-04-03 23:11:33 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-04-09 01:05:17 +00:00
|
|
|
// ParseDurationString parses a string to a duration
|
2020-04-03 23:11:33 +00:00
|
|
|
// Duration notations are an integer followed by a unit
|
|
|
|
// Units are s = second, m = minute, d = day, w = week, M = month, y = year
|
2020-05-02 05:06:39 +00:00
|
|
|
// Example 1y is the same as 1 year.
|
2020-04-09 01:05:17 +00:00
|
|
|
func ParseDurationString(input string) (time.Duration, error) {
|
|
|
|
var duration time.Duration
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2021-08-02 11:55:30 +00:00
|
|
|
matches := reDuration.FindStringSubmatch(input)
|
2020-05-06 00:52:06 +00:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case len(matches) == 3 && matches[2] != "":
|
2020-04-03 23:11:33 +00:00
|
|
|
d, _ := strconv.Atoi(matches[1])
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-04-03 23:11:33 +00:00
|
|
|
switch matches[2] {
|
|
|
|
case "y":
|
|
|
|
duration = time.Duration(d) * Year
|
|
|
|
case "M":
|
|
|
|
duration = time.Duration(d) * Month
|
|
|
|
case "w":
|
|
|
|
duration = time.Duration(d) * Week
|
|
|
|
case "d":
|
|
|
|
duration = time.Duration(d) * Day
|
|
|
|
case "h":
|
|
|
|
duration = time.Duration(d) * Hour
|
|
|
|
case "m":
|
|
|
|
duration = time.Duration(d) * time.Minute
|
|
|
|
case "s":
|
|
|
|
duration = time.Duration(d) * time.Second
|
|
|
|
}
|
2020-05-06 00:52:06 +00:00
|
|
|
case input == "0" || len(matches) == 3:
|
2020-04-03 23:11:33 +00:00
|
|
|
seconds, err := strconv.Atoi(input)
|
|
|
|
if err != nil {
|
2021-07-03 22:08:24 +00:00
|
|
|
return 0, fmt.Errorf("could not convert the input string of %s into a duration: %s", input, err)
|
2020-04-03 23:11:33 +00:00
|
|
|
}
|
2020-05-06 00:52:06 +00:00
|
|
|
|
2020-04-09 01:05:17 +00:00
|
|
|
duration = time.Duration(seconds) * time.Second
|
2020-05-06 00:52:06 +00:00
|
|
|
case input != "":
|
2022-01-31 05:25:15 +00:00
|
|
|
// Throw this error if input is anything other than a blank string, blank string will default to a duration of nothing.
|
2021-07-03 22:08:24 +00:00
|
|
|
return 0, fmt.Errorf("could not convert the input string of %s into a duration", input)
|
2020-04-03 23:11:33 +00:00
|
|
|
}
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-04-09 01:05:17 +00:00
|
|
|
return duration, nil
|
2020-04-03 23:11:33 +00:00
|
|
|
}
|