2020-04-04 06:11:33 +07:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-04-09 08:05:17 +07:00
|
|
|
// ParseDurationString parses a string to a duration
|
2020-04-04 06:11:33 +07: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 12:06:39 +07:00
|
|
|
// Example 1y is the same as 1 year.
|
2020-04-09 08:05:17 +07:00
|
|
|
func ParseDurationString(input string) (time.Duration, error) {
|
|
|
|
var duration time.Duration
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-04-04 06:11:33 +07:00
|
|
|
matches := parseDurationRegexp.FindStringSubmatch(input)
|
2020-05-06 07:52:06 +07:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case len(matches) == 3 && matches[2] != "":
|
2020-04-04 06:11:33 +07:00
|
|
|
d, _ := strconv.Atoi(matches[1])
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-04-04 06:11:33 +07: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 07:52:06 +07:00
|
|
|
case input == "0" || len(matches) == 3:
|
2020-04-04 06:11:33 +07:00
|
|
|
seconds, err := strconv.Atoi(input)
|
|
|
|
if err != nil {
|
2020-04-09 08:05:17 +07:00
|
|
|
return 0, fmt.Errorf("Could not convert the input string of %s into a duration: %s", input, err)
|
2020-04-04 06:11:33 +07:00
|
|
|
}
|
2020-05-06 07:52:06 +07:00
|
|
|
|
2020-04-09 08:05:17 +07:00
|
|
|
duration = time.Duration(seconds) * time.Second
|
2020-05-06 07:52:06 +07:00
|
|
|
case input != "":
|
2020-04-04 06:11:33 +07:00
|
|
|
// Throw this error if input is anything other than a blank string, blank string will default to a duration of nothing
|
2020-04-09 08:05:17 +07:00
|
|
|
return 0, fmt.Errorf("Could not convert the input string of %s into a duration", input)
|
2020-04-04 06:11:33 +07:00
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-04-09 08:05:17 +07:00
|
|
|
return duration, nil
|
2020-04-04 06:11:33 +07:00
|
|
|
}
|