1
0
Fork 0
mirror of https://github.com/Luzifer/go_helpers.git synced 2024-10-18 06:14:21 +00:00

Add helpers to parse time strings using multiple formats at once

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2018-07-05 10:09:39 +02:00
parent 3794ef48bd
commit e9552d47a8
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E

36
time/parse.go Normal file
View file

@ -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
}