gf/util/gconv/gconv_time.go

76 lines
1.8 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gconv
import (
2019-05-07 22:28:34 +08:00
"time"
2019-07-18 18:59:49 +08:00
2020-03-11 23:17:41 +08:00
"github.com/gogf/gf/internal/utils"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/os/gtime"
)
2019-05-08 21:03:04 +08:00
// Time converts <i> to time.Time.
func Time(any interface{}, format ...string) time.Time {
// It's already this type.
if len(format) == 0 {
if v, ok := any.(time.Time); ok {
return v
}
}
if t := GTime(any, format...); t != nil {
2019-07-20 16:41:17 +08:00
return t.Time
}
return time.Time{}
2018-12-16 22:22:07 +08:00
}
// Duration converts <i> to time.Duration.
2019-05-08 21:03:04 +08:00
// If <i> is string, then it uses time.ParseDuration to convert it.
// If <i> is numeric, then it converts <i> as nanoseconds.
func Duration(any interface{}) time.Duration {
// It's already this type.
if v, ok := any.(time.Duration); ok {
return v
}
s := String(any)
2020-03-11 23:17:41 +08:00
if !utils.IsNumeric(s) {
d, _ := gtime.ParseDuration(s)
2019-05-07 22:28:34 +08:00
return d
}
return time.Duration(Int64(any))
2018-12-16 22:22:07 +08:00
}
2019-05-08 21:03:04 +08:00
// GTime converts <i> to *gtime.Time.
// The parameter <format> can be used to specify the format of <i>.
// If no <format> given, it converts <i> using gtime.NewFromTimeStamp if <i> is numeric,
// or using gtime.StrToTime if <i> is string.
func GTime(any interface{}, format ...string) *gtime.Time {
if any == nil {
return nil
}
// It's already this type.
if len(format) == 0 {
if v, ok := any.(*gtime.Time); ok {
return v
}
}
s := String(any)
2019-06-19 09:06:52 +08:00
if len(s) == 0 {
return gtime.New()
}
// Priority conversion using given format.
if len(format) > 0 {
t, _ := gtime.StrToTimeFormat(s, format[0])
return t
}
2020-03-11 23:17:41 +08:00
if utils.IsNumeric(s) {
2019-06-19 09:06:52 +08:00
return gtime.NewFromTimeStamp(Int64(s))
} else {
t, _ := gtime.StrToTime(s)
return t
}
}