diff --git a/util/gconv/gconv_interface.go b/util/gconv/gconv_interface.go index 8ddbe7c3be3..cce763cc0a4 100644 --- a/util/gconv/gconv_interface.go +++ b/util/gconv/gconv_interface.go @@ -6,6 +6,8 @@ package gconv +import "github.com/gogf/gf/os/gtime" + // apiString is used for type assert api for String(). type apiString interface { String() string @@ -92,3 +94,8 @@ type apiUnmarshalText interface { type apiSet interface { Set(value interface{}) (old interface{}) } + +// apiGTime is the interface for gtime.Time converting. +type apiGTime interface { + GTime(format ...string) *gtime.Time +} diff --git a/util/gconv/gconv_time.go b/util/gconv/gconv_time.go index 98aac418dd0..20d9b77b75d 100644 --- a/util/gconv/gconv_time.go +++ b/util/gconv/gconv_time.go @@ -51,11 +51,20 @@ func GTime(any interface{}, format ...string) *gtime.Time { if any == nil { return nil } + if v, ok := any.(apiGTime); ok { + return v.GTime(format...) + } // It's already this type. if len(format) == 0 { if v, ok := any.(*gtime.Time); ok { return v } + if t, ok := any.(time.Time); ok { + return gtime.New(t) + } + if t, ok := any.(*time.Time); ok { + return gtime.New(t) + } } s := String(any) if len(s) == 0 { diff --git a/util/gconv/gconv_z_unit_all_test.go b/util/gconv/gconv_z_unit_all_test.go index 2441e8e6bc6..a358c2362cd 100644 --- a/util/gconv/gconv_z_unit_all_test.go +++ b/util/gconv/gconv_z_unit_all_test.go @@ -647,13 +647,6 @@ func Test_Convert_All(t *testing.T) { }) } -func Test_Time_All(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - t.AssertEQ(gconv.Duration(""), time.Duration(int64(0))) - t.AssertEQ(gconv.GTime(""), gtime.New()) - }) -} - func Test_Slice_All(t *testing.T) { gtest.C(t, func(t *gtest.T) { value := 123.456 diff --git a/util/gconv/gconv_z_unit_time_test.go b/util/gconv/gconv_z_unit_time_test.go index 99d3e01152d..f44acc035e9 100644 --- a/util/gconv/gconv_z_unit_time_test.go +++ b/util/gconv/gconv_z_unit_time_test.go @@ -7,6 +7,7 @@ package gconv_test import ( + "github.com/gogf/gf/container/gvar" "github.com/gogf/gf/frame/g" "testing" "time" @@ -17,6 +18,11 @@ import ( ) func Test_Time(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + t.AssertEQ(gconv.Duration(""), time.Duration(int64(0))) + t.AssertEQ(gconv.GTime(""), gtime.New()) + }) + gtest.C(t, func(t *gtest.T) { s := "2011-10-10 01:02:03.456" t.AssertEQ(gconv.GTime(s), gtime.NewFromStr(s)) @@ -42,6 +48,15 @@ func Test_Time(t *testing.T) { t.AssertEQ(gconv.GTime(s), gtime.NewFromStr(s)) t.AssertEQ(gconv.Time(s), gtime.NewFromStr(s).Time) }) + gtest.C(t, func(t *gtest.T) { + t1 := gtime.NewFromStr("2021-05-21 05:04:51.206547+00") + t2 := gconv.GTime(gvar.New(t1)) + t3 := gvar.New(t1).GTime() + t.AssertEQ(t1, t2) + t.AssertEQ(t1.Local(), t2.Local()) + t.AssertEQ(t1, t3) + t.AssertEQ(t1.Local(), t3.Local()) + }) } func Test_Time_Slice_Attribute(t *testing.T) {