package cast_test import ( "testing" "time" "apigo.cc/go/cast" ) func TestParseTime(t *testing.T) { tests := []struct { input any expected string }{ {"2023-05-04 12:34:56", "2023-05-04 12:34:56"}, {"2023/05/04 12:34:56", "2023-05-04 12:34:56"}, {"2023.05.04 12:34:56", "2023-05-04 12:34:56"}, {"20230504123456", "2023-05-04 12:34:56"}, {1683196496, "2023-05-04 10:34:56"}, // Unix timestamp (Example) {"2023年5月4日 12时34分56秒", "2023-05-04 12:34:56"}, } // Set UTC for test stability if needed, or just compare formatted strings loc, _ := time.LoadLocation("UTC") cast.SetDefaultTimeZone(loc) for _, tt := range tests { tm := cast.ParseTime(tt.input) // We use a relative check for timestamp since it depends on the timezone if not careful if tt.input == 1683196496 { // 1683196496 is 2023-05-04 10:34:56 UTC if tm.Format("2006-01-02 15:04:05") != tt.expected { t.Errorf("ParseTime(%v) = %v, want %v", tt.input, tm.Format("2006-01-02 15:04:05"), tt.expected) } continue } if tm.Format("2006-01-02 15:04:05") != tt.expected { t.Errorf("ParseTime(%v) = %v, want %v", tt.input, tm.Format("2006-01-02 15:04:05"), tt.expected) } } } func TestFormatTime(t *testing.T) { tm := time.Date(2023, 5, 4, 12, 34, 56, 0, time.UTC) formatted := cast.FormatTime("YYYY-MM-DD HH:mm:ss", tm) if formatted != "2023-05-04 12:34:56" { t.Errorf("FormatTime failed, got %s", formatted) } } func TestAddTime(t *testing.T) { tm := time.Date(2023, 5, 4, 12, 34, 56, 0, time.UTC) added := cast.AddTime("+1Y+1M+1D", tm) expected := time.Date(2024, 6, 5, 12, 34, 56, 0, time.UTC) if !added.Equal(expected) { t.Errorf("AddTime failed, got %v, want %v", added, expected) } } func TestTimeZoneNow(t *testing.T) { loc, _ := time.LoadLocation("Asia/Shanghai") tz := cast.NewTimeZone(loc) now := tz.Now() if now.Location().String() != "Asia/Shanghai" { t.Errorf("TimeZone.Now() failed to set location, got %s", now.Location().String()) } }