github.com/hzck/speedroute@v0.0.0-20201115191102-403b7d0e443f/parser/timeparser.go (about) 1 package parser 2 3 import ( 4 "errors" 5 "math" 6 "strconv" 7 "strings" 8 ) 9 10 // StoMS is the factor which needs to be multiplies when converting seconds to milliseconds (1000). 11 const StoMS = 1000 12 13 // MtoMS is the factor which needs to be multiplies when converting minutes to milliseconds (60*1000). 14 const MtoMS = 60 * StoMS 15 16 // HtoMS is the factor which needs to be multiplies when converting hours to milliseconds (60*60*1000). 17 const HtoMS = 60 * MtoMS 18 19 const onlySec = 1 20 const minSec = 2 21 const hourMinSec = 3 22 23 func parseTime(time string) (int, error) { 24 times := strings.Split(time, ":") 25 var h, m, s string 26 switch len(times) { 27 case onlySec: 28 s = times[0] 29 case minSec: 30 m = times[0] 31 s = times[1] 32 case hourMinSec: 33 h = times[0] 34 m = times[1] 35 s = times[2] 36 default: 37 return -1, errors.New("Can't parse time " + time) 38 } 39 result := 0 40 if len(h) > 0 { 41 hours, err := parseInt(h) 42 if err != nil { 43 return -1, err 44 } 45 result += hours * HtoMS 46 } 47 if len(m) > 0 { 48 mins, err := parseInt(m) 49 if err != nil { 50 return -1, err 51 } 52 result += mins * MtoMS 53 } 54 if len(s) > 0 { 55 if strings.Contains(s, ".") || len(m) > 0 { 56 secs, err := parseSeconds(s) 57 if err != nil { 58 return -1, err 59 } 60 result += secs 61 } else { 62 ms, err := parseInt(s) 63 if err != nil { 64 return -1, err 65 } 66 result += ms 67 } 68 } 69 70 return result, nil 71 } 72 73 func parseInt(time string) (int, error) { 74 result, err := strconv.ParseInt(time, 10, 0) 75 if err != nil { 76 return -1, err 77 } 78 return int(result), nil 79 } 80 81 func parseSeconds(time string) (int, error) { 82 if time == "." { 83 return 0, nil 84 } 85 result, err := strconv.ParseFloat(time, 64) 86 if err != nil { 87 return -1, err 88 } 89 return int(math.Round(result * StoMS)), nil 90 }