mirror of
https://github.com/Luzifer/go_helpers.git
synced 2024-12-24 13:01: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:
parent
3794ef48bd
commit
e9552d47a8
1 changed files with 36 additions and 0 deletions
36
time/parse.go
Normal file
36
time/parse.go
Normal 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
|
||||||
|
}
|
Loading…
Reference in a new issue