diff --git a/datetime/datetime.go b/datetime/datetime.go index 5523ca6..f3eac72 100644 --- a/datetime/datetime.go +++ b/datetime/datetime.go @@ -188,15 +188,13 @@ func GetTodayEndTime() string { // GetZeroHourTimestamp return timestamp of zero hour (timestamp of 00:00). // Play: https://go.dev/play/p/QmL2oIaGE3q func GetZeroHourTimestamp() int64 { - ts := time.Now().Format("2006-01-02") - t, _ := time.Parse("2006-01-02", ts) - return t.UTC().Unix() - 8*3600 + return BeginOfDay(time.Now()).Unix() } // GetNightTimestamp return timestamp of zero hour (timestamp of 23:59). // Play: https://go.dev/play/p/UolysR3MYP1 func GetNightTimestamp() int64 { - return GetZeroHourTimestamp() + 86400 - 1 + return EndOfDay(time.Now()).Unix() } // FormatTimeToStr convert time to string. diff --git a/datetime/datetime_test.go b/datetime/datetime_test.go index ed547a9..be185be 100644 --- a/datetime/datetime_test.go +++ b/datetime/datetime_test.go @@ -943,3 +943,28 @@ func TestBetweenSeconds(t *testing.T) { assert.Equal(int64(86400), result1) assert.Equal(int64(-86400), result2) } + +func TestGetZeroHourAndNightTimestampLocalZone(t *testing.T) { + // not parallel: this test replaces time.Local + assert := internal.NewAssert(t, "TestGetZeroHourAndNightTimestampLocalZone") + + oldLocal := time.Local + defer func() { time.Local = oldLocal }() + + for _, offset := range []int{-5 * 3600, 0, 8 * 3600, 9 * 3600} { + time.Local = time.FixedZone("test", offset) + + before := time.Now() + zero := GetZeroHourTimestamp() + night := GetNightTimestamp() + after := time.Now() + + if before.Day() != after.Day() { + continue + } + + assert.Equal(BeginOfDay(before).Unix(), zero) + assert.Equal(EndOfDay(before).Unix(), night) + assert.Equal(int64(86399), night-zero) + } +}