Merge pull request #560 from brian-brazil/almost-human
Better handling of edge conditions in humanizeDuration
This commit is contained in:
commit
78cf64bf1d
|
@ -188,22 +188,22 @@ func NewTemplateExpander(text string, name string, data interface{}, timestamp c
|
|||
sign = "-"
|
||||
v = -v
|
||||
}
|
||||
seconds := math.Mod(v, 60)
|
||||
seconds := int64(v) % 60
|
||||
minutes := (int64(v) / 60) % 60
|
||||
hours := (int64(v) / 60 / 60) % 24
|
||||
days := (int64(v) / 60 / 60 / 24)
|
||||
// For days to minutes, we display seconds as an integer.
|
||||
if days != 0 {
|
||||
return fmt.Sprintf("%s%dd %dh %dm %.0fs", sign, days, hours, minutes, seconds)
|
||||
return fmt.Sprintf("%s%dd %dh %dm %ds", sign, days, hours, minutes, seconds)
|
||||
}
|
||||
if hours != 0 {
|
||||
return fmt.Sprintf("%s%dh %dm %.0fs", sign, hours, minutes, seconds)
|
||||
return fmt.Sprintf("%s%dh %dm %ds", sign, hours, minutes, seconds)
|
||||
}
|
||||
if minutes != 0 {
|
||||
return fmt.Sprintf("%s%dm %.0fs", sign, minutes, seconds)
|
||||
return fmt.Sprintf("%s%dm %ds", sign, minutes, seconds)
|
||||
}
|
||||
// For seconds, we display 4 significant digts.
|
||||
return fmt.Sprintf("%s%.4gs", sign, math.Floor(seconds*1000+.5)/1000)
|
||||
return fmt.Sprintf("%s%.4gs", sign, v)
|
||||
}
|
||||
prefix := ""
|
||||
for _, p := range []string{"m", "u", "n", "p", "f", "a", "z", "y"} {
|
||||
|
|
|
@ -113,14 +113,14 @@ func TestTemplateExpansion(t *testing.T) {
|
|||
{
|
||||
// HumanizeDuration - seconds.
|
||||
text: "{{ range . }}{{ humanizeDuration . }}:{{ end }}",
|
||||
input: []float64{0, 1, 60, 3600, 86400, 86400 + 3600, -(86400*2 + 3600*3 + 60*4 + 5)},
|
||||
output: "0s:1s:1m 0s:1h 0m 0s:1d 0h 0m 0s:1d 1h 0m 0s:-2d 3h 4m 5s:",
|
||||
input: []float64{0, 1, 60, 3600, 86400, 86400 + 3600, -(86400*2 + 3600*3 + 60*4 + 5), 899.99},
|
||||
output: "0s:1s:1m 0s:1h 0m 0s:1d 0h 0m 0s:1d 1h 0m 0s:-2d 3h 4m 5s:14m 59s:",
|
||||
},
|
||||
{
|
||||
// HumanizeDuration - subsecond and fractional seconds.
|
||||
text: "{{ range . }}{{ humanizeDuration . }}:{{ end }}",
|
||||
input: []float64{.1, .0001, .12345, 60.1, 60.5, 1.2345, 12.345},
|
||||
output: "100ms:100us:123.5ms:1m 0s:1m 0s:1.235s:12.35s:",
|
||||
output: "100ms:100us:123.5ms:1m 0s:1m 0s:1.234s:12.35s:",
|
||||
},
|
||||
{
|
||||
// Title.
|
||||
|
|
Loading…
Reference in New Issue