Skip to content

Commit 8692bfc

Browse files
committed
Change FormatDuration to be consistent across language implementations
1 parent e6abec2 commit 8692bfc

1 file changed

Lines changed: 27 additions & 22 deletions

File tree

pkg/utils/duration.go

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ func FormatDuration(duration time.Duration) (string, error) {
6767
6868
Returns: string or error if duration cannot be expressed as a GEP-2257 Duration format.
6969
*/
70+
7071
if duration == 0 {
7172
return "0s", nil
7273
}
@@ -86,37 +87,41 @@ func FormatDuration(duration time.Duration) (string, error) {
8687
return "", errors.New("Cannot express sub-milliseconds precision in GEP-2257")
8788
}
8889

89-
// Golang's time.Duration allows for floating point seconds instead of converting to ms
90-
durationMilliseconds := duration.Milliseconds()
90+
output := ""
91+
seconds := int(duration.Seconds())
92+
93+
// calculating the hours
94+
hours := int(seconds / 3600)
95+
96+
if hours > 0 {
97+
output += fmt.Sprintf("%dh", hours)
98+
seconds -= hours * 3600
99+
}
100+
101+
// calculating the minutes
102+
minutes := int(seconds / 60)
91103

92-
var ms int64
93-
if durationMilliseconds%1000 != 0 {
94-
ms = durationMilliseconds % 1000
95-
durationMilliseconds -= ms
96-
duration = time.Millisecond * time.Duration(durationMilliseconds)
104+
if minutes > 0 {
105+
output += fmt.Sprintf("%dm", minutes)
106+
seconds -= minutes * 60
97107
}
98108

99-
durationString := duration.String()
100-
if ms > 0 {
101-
durationString += fmt.Sprintf("%dms", ms)
109+
if seconds > 0 {
110+
output += fmt.Sprintf("%ds", seconds)
102111
}
103112

104-
// trim the 0 values from the string (for example, 30m0s should result in 30m)
105-
// going to have a regexp that finds the index of the time units with 0, then appropriately trim those away
106-
temp := reSplit.FindAll([]byte(durationString), -1)
107-
res := ""
108-
for _, t := range temp {
109-
if t[0] != '0' {
110-
res += string(t)
111-
} else {
112-
continue
113-
}
113+
// Golang's time.Duration allows for floating point seconds instead of converting to ms
114+
durationMilliseconds := durationMicroseconds / 1000
115+
116+
ms := durationMilliseconds % 1000
117+
if ms != 0 {
118+
output += fmt.Sprintf("%dms", ms)
114119
}
115120

116121
// check if there are floating number points
117-
if !re.MatchString(res) {
122+
if !re.MatchString(output) {
118123
return "", errors.New("Invalid duration format")
119124
}
120125

121-
return res, nil
126+
return output, nil
122127
}

0 commit comments

Comments
 (0)