From a0552a237c93930e98af8a217a4dd0bd95118535 Mon Sep 17 00:00:00 2001 From: Andreas Paul Date: Fri, 14 Oct 2016 18:11:48 +0200 Subject: [PATCH] allow to specify time unit for time elapsed --- bar.go | 5 +++++ util/strutil/strutil.go | 8 ++++++++ util/strutil/strutil_test.go | 16 ++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/bar.go b/bar.go index 6c27be2..b26c210 100644 --- a/bar.go +++ b/bar.go @@ -235,3 +235,8 @@ func (b *Bar) TimeElapsed() time.Duration { func (b *Bar) TimeElapsedString() string { return strutil.PrettyTime(b.TimeElapsed()) } + +// TimeElapsedStringFormat returns the formatted string represenation of the time elapsed in the specified time unit +func (b *Bar) TimeElapsedStringFormat(f time.Duration) string { + return strutil.PrettyTimeFormat(b.TimeElapsed(), f) +} diff --git a/util/strutil/strutil.go b/util/strutil/strutil.go index 7638ae5..4cba2b9 100644 --- a/util/strutil/strutil.go +++ b/util/strutil/strutil.go @@ -59,3 +59,11 @@ func PrettyTime(t time.Duration) string { } return (t - (t % time.Second)).String() } + +// PrettyTimeFormat returns the string representation of the duration. It rounds the time duration to the specified unit and returns a "---" when duration is 0 +func PrettyTimeFormat(t time.Duration, f time.Duration) string { + if t == 0 { + return "---" + } + return (t - (t % f)).String() +} diff --git a/util/strutil/strutil_test.go b/util/strutil/strutil_test.go index fa5a133..5dba3cb 100644 --- a/util/strutil/strutil_test.go +++ b/util/strutil/strutil_test.go @@ -40,3 +40,19 @@ func TestPrettyTime(t *testing.T) { t.Fatal("want", "---", "got", got) } } + +func TestPrettyTimeFormat(t *testing.T) { + d, _ := time.ParseDuration("300ms") + got := PrettyTimeFormat(d, time.Millisecond) + if got != "300ms" { + t.Fatal("want", "300ms", "got", got) + } + got = PrettyTimeFormat(d, time.Second) + if got != "0s" { + t.Fatal("want", "0s", "got", got) + } + got = PrettyTimeFormat(d, time.Hour) + if got != "0s" { + t.Fatal("want", "0s", "got", got) + } +}