From e9552d47a8cb67a7e66a2ada17e8512487ba031a Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Thu, 5 Jul 2018 10:09:39 +0200 Subject: [PATCH] Add helpers to parse time strings using multiple formats at once Signed-off-by: Knut Ahlers --- time/parse.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 time/parse.go diff --git a/time/parse.go b/time/parse.go new file mode 100644 index 0000000..d4564f9 --- /dev/null +++ b/time/parse.go @@ -0,0 +1,36 @@ +package time + +import ( + "errors" + gotime "time" +) + +// ErrParseNotPossible describes a collected error which is returned +// when the given date value could not be parsed with any given layout +var ErrParseNotPossible = errors.New("No layout matched given value or other error occurred") + +// MultiParse takes multiple layout strings and tries to parse the +// value with them. In case none of the layouts matches or another error +// occurs ErrParseNotPossible is returned +func MultiParse(layouts []string, value string) (gotime.Time, error) { + for _, layout := range layouts { + if t, err := gotime.Parse(layout, value); err == nil { + return t, nil + } + } + + return gotime.Time{}, ErrParseNotPossible +} + +// MultiParseInLocation takes multiple layouts and tries to parse the +// value with them using time.ParseInLocation. In case none of the layouts +// matches or another error occurs ErrParseNotPossible is returned +func MultiParseInLocation(layouts []string, value string, loc *gotime.Location) (gotime.Time, error) { + for _, layout := range layouts { + if t, err := gotime.ParseInLocation(layout, value, loc); err == nil { + return t, nil + } + } + + return gotime.Time{}, ErrParseNotPossible +}