package test import ( "errors" "fmt" "testing" "time" ) /*周期记录时间测试 1、2、5、6、10、10、15、20、30、60 */ func TestPeriod(t *testing.T) { //// 更新记录 - 缓存 // 输入时间列表 timeStrings := []string{ "2017-04-11 13:00:00", "2017-04-11 13:01:01", "2017-04-11 13:02:12", "2017-04-11 13:03:12", "2017-04-11 13:04:12", "2017-04-11 13:05:12", "2017-04-11 13:06:12", "2017-04-11 13:07:12", "2017-04-11 13:08:12", "2017-04-11 13:09:12", "2017-04-11 13:10:12", "2017-04-11 13:20:32", "2017-02-12 13:22:12", "2017-03-13 13:24:45", "2024-04-14 13:26:10", "2024-04-15 13:29:59", "2023-04-11 13:30:10", "2023-05-11 13:33:23", "2023-05-11 13:39:38", "2023-05-11 13:41:23", "2023-05-11 13:43:34", "2023-05-11 13:54:30", "2023-05-11 13:50:00", "2023-05-11 13:51:00", "2023-05-11 13:52:00", "2023-05-11 13:53:00", "2023-05-11 13:54:00", "2023-05-11 13:55:12", "2023-05-11 13:56:19", "2023-05-11 13:56:29", "2023-05-11 13:58:49", "2023-05-11 13:59:59", "2023-05-11 14:00:05", "2023-05-11 14:01:05", "2023-05-11 14:01:15", "2023-05-11 14:02:05", "2023-05-11 14:03:05", "2023-05-11 14:04:05", "2023-05-11 14:05:05", "2023-05-11 14:06:05", "2023-05-11 14:07:05", "2023-05-11 14:08:05", "2023-05-11 14:09:05", "2023-05-11 14:10:05", "2024-09-30 00:30:00", } for _, ts := range timeStrings { time_r, err := PeriodTime(ts, 30) if err != nil { fmt.Println(err) } fmt.Println(time_r.Format("2006-01-02 15:04:05")) } } func PeriodTime(time_s string, T_saveT int) (time.Time, error) { period := time.Minute * time.Duration(T_saveT) // 解析时间字符串 t, err := time.Parse("2006-01-02 15:04:05", time_s) if err != nil { fmt.Println("时间解析错误:", err) return time.Now(), errors.New("时间解析错误!") } // 计算归一化的分钟 minutes := t.Minute() normalizedMinutes := (minutes / int(period.Minutes())) * int(period.Minutes()) // 创建新的时间对象,使用归一化后的分钟 normalizedTime := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), normalizedMinutes, 0, 0, t.Location()) // 输出结果 //fmt.Println(normalizedTime.Format("2006-01-02 15:04:05")) return normalizedTime, nil }