diff --git a/date.go b/date.go index d1d6155d..1cbdea52 100644 --- a/date.go +++ b/date.go @@ -73,6 +73,50 @@ func dateAgo(date interface{}) string { return duration.String() } +func durationRound(duration interface{}) string { + var d time.Duration + switch duration := duration.(type) { + default: + d = 0 + case string: + d, _ = time.ParseDuration(duration) + case int64: + d = time.Duration(duration) + case time.Time: + d = time.Since(duration) + } + + u := uint64(d) + neg := d < 0 + if neg { + u = -u + } + + var ( + year = uint64(time.Hour) * 24 * 365 + month = uint64(time.Hour) * 24 * 30 + day = uint64(time.Hour) * 24 + hour = uint64(time.Hour) + minute = uint64(time.Minute) + second = uint64(time.Second) + ) + switch { + case u > year: + return strconv.FormatUint(u/year, 10) + "y" + case u > month: + return strconv.FormatUint(u/month, 10) + "mo" + case u > day: + return strconv.FormatUint(u/day, 10) + "d" + case u > hour: + return strconv.FormatUint(u/hour, 10) + "h" + case u > minute: + return strconv.FormatUint(u/minute, 10) + "m" + case u > second: + return strconv.FormatUint(u/second, 10) + "s" + } + return "0s" +} + func toDate(fmt, str string) time.Time { t, _ := time.ParseInLocation(fmt, str, time.Local) return t diff --git a/date_test.go b/date_test.go index a81ecf96..78bf1c29 100644 --- a/date_test.go +++ b/date_test.go @@ -91,3 +91,16 @@ func TestDateInZone(t *testing.T) { t.Error(err) } } + +func TestDurationRound(t *testing.T) { + tpl := "{{ durationRound .Time }}" + if err := runtv(tpl, "2h", map[string]interface{}{"Time": "2h5s"}); err != nil { + t.Error(err) + } + if err := runtv(tpl, "1d", map[string]interface{}{"Time": "24h5s"}); err != nil { + t.Error(err) + } + if err := runtv(tpl, "3mo", map[string]interface{}{"Time": "2400h5s"}); err != nil { + t.Error(err) + } +} diff --git a/functions.go b/functions.go index 45e9d5ae..0ae724eb 100644 --- a/functions.go +++ b/functions.go @@ -91,15 +91,16 @@ var genericMap = map[string]interface{}{ "hello": func() string { return "Hello!" }, // Date functions + "ago": dateAgo, "date": date, + "dateInZone": dateInZone, + "dateModify": dateModify, "date_in_zone": dateInZone, "date_modify": dateModify, - "now": func() time.Time { return time.Now() }, + "durationRound": durationRound, "htmlDate": htmlDate, "htmlDateInZone": htmlDateInZone, - "dateInZone": dateInZone, - "dateModify": dateModify, - "ago": dateAgo, + "now": func() time.Time { return time.Now() }, "toDate": toDate, "unixEpoch": unixEpoch, @@ -295,5 +296,5 @@ var genericMap = map[string]interface{}{ // URLs: "urlParse": urlParse, - "urlJoin": urlJoin, + "urlJoin": urlJoin, }