Skip to content

Commit

Permalink
time codec fix
Browse files Browse the repository at this point in the history
  • Loading branch information
deze333 committed Nov 27, 2014
1 parent 9cf338c commit 041104d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 39 deletions.
78 changes: 41 additions & 37 deletions codec_time.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package xparam

import (
"fmt"
"errors"
"fmt"
"strconv"
"time"
)
Expand All @@ -15,51 +16,54 @@ import (
// 30d, 77h, 99m
func StringToDuration(val string) (dt time.Duration, err error) {

num := 0
l := len(val)
num, err = strconv.Atoi(val[0:l - 1])
if err != nil {
return
}
num := 0
l := len(val)
if l == 0 {
err = errors.New("Cannot convert empty string to duration")
return
}
num, err = strconv.Atoi(val[0 : l-1])
if err != nil {
return
}

switch val[l - 1:l] {
case "d":
dt = time.Duration(num) * 24 * time.Hour
case "h":
dt = time.Duration(num) * time.Hour
case "m":
dt = time.Duration(num) * time.Minute
default:
err = fmt.Errorf("Time duration must end with d/h/m: %v", val)
}
return
switch val[l-1 : l] {
case "d":
dt = time.Duration(num) * 24 * time.Hour
case "h":
dt = time.Duration(num) * time.Hour
case "m":
dt = time.Duration(num) * time.Minute
default:
err = fmt.Errorf("Time duration must end with d/h/m: %v", val)
}
return
}

// Converts duration into string notation, ie:
// 1d, 1h, 1m
// The smallest interval is 1m. Smaller values replaced with 1m.
func DurationToString(dt time.Duration) string {
h := dt / time.Hour
hm := dt % time.Hour
d := h / 24
dh := dt % (24 * time.Hour)
h := dt / time.Hour
hm := dt % time.Hour
d := h / 24
dh := dt % (24 * time.Hour)

// If matches whole day
if d > 0 && dh == 0 {
return fmt.Sprintf("%dd", d)
}
// If matches whole day
if d > 0 && dh == 0 {
return fmt.Sprintf("%dd", d)
}

// If matches whole hour
if h > 0 && hm == 0 {
return fmt.Sprintf("%dh", h)
}
// If matches whole hour
if h > 0 && hm == 0 {
return fmt.Sprintf("%dh", h)
}

// Otherwise make into minutes
m := dt / time.Minute
if m > 0 {
return fmt.Sprintf("%dm", m)
}
// Otherwise make into minutes
m := dt / time.Minute
if m > 0 {
return fmt.Sprintf("%dm", m)
}

return "1m"
return "1m"
}

10 changes: 8 additions & 2 deletions xp_meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,19 @@ func asArray_Duration(data string) (vals []time.Duration, err error) {
vals = make([]time.Duration, len(ss))
var v time.Duration

for i, s := range ss {
idx := 0
for _, s := range ss {
s = strings.TrimSpace(s)
if s == "" {
continue
}
if v, err = StringToDuration(s); err == nil {
vals[i] = v
vals[idx] = v
idx++
} else {
return
}
}
vals = vals[0:idx]
return
}

0 comments on commit 041104d

Please sign in to comment.