Skip to content

Commit

Permalink
Make GTime support multiple formats (gogf#2933)
Browse files Browse the repository at this point in the history
  • Loading branch information
bigger-boss authored Sep 13, 2023
1 parent 5219c5c commit e684eae
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
16 changes: 9 additions & 7 deletions os/gtime/gtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 8 additions & 2 deletions util/gconv/gconv_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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))
Expand Down

0 comments on commit e684eae

Please sign in to comment.