github.com/hungdoo/bot@v0.0.0-20240325145135-dd1f386f7b81/src/packages/utils/time.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "regexp" 6 "strconv" 7 "strings" 8 "time" 9 ) 10 11 func ParseCustomDuration(durationString string) (time.Duration, error) { 12 // Split the string into number and unit 13 re := regexp.MustCompile(`(\d+)(\w)`) 14 matches := re.FindStringSubmatch(durationString) 15 16 if len(matches) != 3 { // matches[0] is the durationString 17 return 0, fmt.Errorf("invalid duration format: %s -> %v", durationString, matches) 18 } 19 20 // Parse the number part 21 num, err := strconv.Atoi(matches[1]) 22 if err != nil { 23 return 0, fmt.Errorf("failed to parse duration number: %v", err) 24 } 25 26 // Map the unit to a time.Duration 27 unit := strings.ToLower(matches[2]) 28 switch unit { 29 case "s": 30 return time.Duration(num) * time.Second, nil 31 case "m": 32 return time.Duration(num) * time.Minute, nil 33 case "h": 34 return time.Duration(num) * time.Hour, nil 35 // Add more units as needed 36 37 default: 38 return 0, fmt.Errorf("unsupported duration unit: %s", unit) 39 } 40 }