mirror of
https://gitee.com/johng/gf.git
synced 2024-11-30 03:07:45 +08:00
Make GTime support multiple formats (#2933)
This commit is contained in:
parent
5219c5c37e
commit
e684eae878
@ -363,19 +363,21 @@ func StrToTimeLayout(str string, layout string) (*Time, error) {
|
||||
// ParseTimeFromContent retrieves time information for content string, it then parses and returns it
|
||||
// as *Time object.
|
||||
// It returns the first time information if there are more than one time string in the content.
|
||||
// It only retrieves and parses the time information with given `format` if it's passed.
|
||||
// It only retrieves and parses the time information with given first matched `format` if it's passed.
|
||||
func ParseTimeFromContent(content string, format ...string) *Time {
|
||||
var (
|
||||
err error
|
||||
match []string
|
||||
)
|
||||
if len(format) > 0 {
|
||||
match, err = gregex.MatchString(formatToRegexPattern(format[0]), content)
|
||||
if err != nil {
|
||||
intlog.Errorf(context.TODO(), `%+v`, err)
|
||||
}
|
||||
if len(match) > 0 {
|
||||
return NewFromStrFormat(match[0], format[0])
|
||||
for _, item := range format {
|
||||
match, err = gregex.MatchString(formatToRegexPattern(item), content)
|
||||
if err != nil {
|
||||
intlog.Errorf(context.TODO(), `%+v`, err)
|
||||
}
|
||||
if len(match) > 0 {
|
||||
return NewFromStrFormat(match[0], item)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if match = timeRegex1.FindStringSubmatch(content); len(match) >= 1 {
|
||||
|
@ -45,6 +45,7 @@ func Duration(any interface{}) time.Duration {
|
||||
|
||||
// GTime converts `any` to *gtime.Time.
|
||||
// The parameter `format` can be used to specify the format of `any`.
|
||||
// It returns the converted value that matched the first format of the formats slice.
|
||||
// If no `format` given, it converts `any` using gtime.NewFromTimeStamp if `any` is numeric,
|
||||
// or using gtime.StrToTime if `any` is string.
|
||||
func GTime(any interface{}, format ...string) *gtime.Time {
|
||||
@ -72,8 +73,13 @@ func GTime(any interface{}, format ...string) *gtime.Time {
|
||||
}
|
||||
// Priority conversion using given format.
|
||||
if len(format) > 0 {
|
||||
t, _ := gtime.StrToTimeFormat(s, format[0])
|
||||
return t
|
||||
for _, item := range format {
|
||||
t, err := gtime.StrToTimeFormat(s, item)
|
||||
if t != nil && err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if utils.IsNumeric(s) {
|
||||
return gtime.NewFromTimeStamp(Int64(s))
|
||||
|
Loading…
Reference in New Issue
Block a user