From 2285105a158822008bf9441b9b5a7e794eb3b70a Mon Sep 17 00:00:00 2001 From: Dave Henderson Date: Thu, 19 Apr 2018 00:44:40 -0400 Subject: Adding time.ParseDuration function Signed-off-by: Dave Henderson --- docs/content/functions/time.md | 27 +++++++++++++++++++++++++++ funcs/time.go | 5 +++++ 2 files changed, 32 insertions(+) diff --git a/docs/content/functions/time.md b/docs/content/functions/time.md index 2bd342a2..902f3d78 100644 --- a/docs/content/functions/time.md +++ b/docs/content/functions/time.md @@ -72,6 +72,8 @@ $ gomplate -i '{{ (time.Now).Format time.Kitchen }} 11:05AM ``` +For other durations, such as `2h10m`, [`time.ParseDuration`](#time-parseduration) can be used. + ## `time.Now` Returns the current local time, as a `time.Time`. This wraps [`time.Now`](https://golang.org/pkg/time/#Now). @@ -133,6 +135,31 @@ $ gomplate -i '{{ (time.Parse "2006-01-02" "1993-10-23").Format "Monday January Saturday October 23, 1993 UTC ``` +## `time.ParseDuration` + +Parses a duration string. This wraps [`time.ParseDuration`](https://golang.org/pkg/time/#ParseDuration). + +A duration string is a possibly signed sequence of decimal numbers, each with +optional fraction and a unit suffix, such as `300ms`, `-1.5h` or `2h45m`. Valid +time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. + +### Usage +```go +time.ParseDuration duration +``` +```go +duration | time.ParseDuration +``` + +### Examples + +```console +$ gomplate -i '{{ (time.Now).Format time.Kitchen }} +{{ ((time.Now).Add (time.ParseDuration "2h30m")).Format time.Kitchen }}' +12:43AM +3:13AM +``` + ## `time.ParseLocal` Same as [`time.Parse`](#time-parse), except that in the absence of a time zone diff --git a/funcs/time.go b/funcs/time.go index a1940584..111b0b23 100644 --- a/funcs/time.go +++ b/funcs/time.go @@ -138,6 +138,11 @@ func (f *TimeFuncs) Hour(n interface{}) gotime.Duration { return gotime.Hour * gotime.Duration(conv.ToInt64(n)) } +// ParseDuration - +func (f *TimeFuncs) ParseDuration(n interface{}) (gotime.Duration, error) { + return gotime.ParseDuration(conv.ToString(n)) +} + // convert a number input to a pair of int64s, representing the integer portion and the decimal remainder // this can handle a string as well as any integer or float type // precision is at the "nano" level (i.e. 1e+9) -- cgit v1.2.3