From f17cb5291c9f78fad9fb574d8b8731de9a98f03d Mon Sep 17 00:00:00 2001 From: R22627 Date: Mon, 13 Nov 2023 17:17:55 +0800 Subject: [PATCH] feat:add new time util function GetBeijingTime --- go.mod | 2 +- time/time.go | 11 +++++++++++ time/time_test.go | 12 ++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 2456bc1..c063163 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/dablelv/cyan -go 1.19 +go 1.21 require ( golang.org/x/exp v0.0.0-20221229233502-02c3fc3b3eb4 diff --git a/time/time.go b/time/time.go index 5bce9a7..286c157 100644 --- a/time/time.go +++ b/time/time.go @@ -223,3 +223,14 @@ func IsSameWeek(ts1, ts2 int64) bool { t2 := time.Unix(ts2, 0) return GetMonDate(t1) == GetMonDate(t2) } + +// GetBeijingTime gets Beijing Time from time string and layout. +// The location name Asia/Shanghai from IANA Time Zone Database standards for Beijing Time. +func GetBeijingTime(layout, value string) (t time.Time, err error) { + location, err := time.LoadLocation("Asia/Shanghai") + if err != nil { + return + } + t, err = time.ParseInLocation(layout, value, location) + return +} diff --git a/time/time_test.go b/time/time_test.go index 6a59586..c49214b 100644 --- a/time/time_test.go +++ b/time/time_test.go @@ -2,6 +2,7 @@ package time import ( "testing" + "time" "github.com/dablelv/cyan/internal" ) @@ -197,3 +198,14 @@ func TestIsSameWeek(t *testing.T) { assert.Equal(tt.want, got) } } + +func TestGetBeijingTime(t *testing.T) { + assert := internal.NewAssert(t, "TestGetBeijingTime") + + got, err := GetBeijingTime(time.DateTime, "2022-11-04 08:30:00") + assert.IsNil(err) + assert.Equal("2022-11-04 08:30:00", got.Format(time.DateTime)) + + _, err = GetBeijingTime(time.RFC3339, "2022-11-04 08:30:00") + assert.IsNotNil(err) +}