统一时间格式和时区
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package timeutil
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
APITimeLayout = "2006-01-02T15:04:05-07:00"
|
||||
OrderNoLayout = "20060102150405"
|
||||
)
|
||||
|
||||
var businessLocation = time.FixedZone("CST", 8*60*60)
|
||||
|
||||
func Location() *time.Location {
|
||||
return businessLocation
|
||||
}
|
||||
|
||||
func Now() time.Time {
|
||||
return time.Now().In(businessLocation)
|
||||
}
|
||||
|
||||
func FormatAPITime(value time.Time) string {
|
||||
if value.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return value.In(businessLocation).Truncate(time.Second).Format(APITimeLayout)
|
||||
}
|
||||
|
||||
func StartOfDay(value time.Time) time.Time {
|
||||
local := value.In(businessLocation)
|
||||
year, month, day := local.Date()
|
||||
return time.Date(year, month, day, 0, 0, 0, 0, businessLocation)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package timeutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFormatAPITimeUsesBusinessTimezone(t *testing.T) {
|
||||
value := time.Date(2026, 7, 30, 9, 53, 58, 147355000, time.UTC)
|
||||
if got := FormatAPITime(value); got != "2026-07-30T17:53:58+08:00" {
|
||||
t.Fatalf("unexpected api time: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartOfDayUsesBusinessTimezone(t *testing.T) {
|
||||
value := time.Date(2026, 7, 30, 18, 30, 0, 0, time.UTC)
|
||||
got := StartOfDay(value)
|
||||
if got.Format(APITimeLayout) != "2026-07-31T00:00:00+08:00" {
|
||||
t.Fatalf("unexpected day start: %s", got.Format(APITimeLayout))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user