package util import ( "fmt" "strconv" "time" ) func ZeroTimestamp() int64 { now := time.Now() midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) return midnight.Unix() } func GetHour(ts int64, tz string) int { loc, _ := time.LoadLocation(tz) return time.Unix(ts, 0).In(loc).Hour() } // 将ISO 8601格式的时间字符串转换为指定时区的时间戳 // timeStr: ISO 8601格式的时间字符串,如:"2025-03-17T16:00:00.000Z" // timezone: 时区字符串,如:"Asia/Shanghai","America/New_York",留空则使用UTC func ParseTimeToTimestamp(timeStr string, timezone string) (int64, error) { // 如果 timeStr 是纯数字,则直接解析为时间戳返回 if ts, err := strconv.ParseInt(timeStr, 10, 64); err == nil { return ts, nil } // 先解析为UTC时间 t, err := time.Parse(time.RFC3339, timeStr) if err != nil { return 0, err } // 如果没有指定时区,直接返回UTC时间戳 if timezone == "" { return t.Unix(), nil } // 加载指定时区 loc, err := time.LoadLocation(timezone) if err != nil { return 0, fmt.Errorf("invalid timezone: %v", err) } // 将时间转换到指定时区 t = t.In(loc) return t.Unix(), nil } // GetZeroTimestamp 获取指定时区的当天0点时间戳 // timezone: 时区字符串,如:"Asia/Shanghai","America/New_York",留空则使用UTC // offset: 日期偏移,0表示今天,-1表示昨天,1表示明天,以此类推 func GetZeroTimestamp(timezone string, offset int) (int64, error) { var loc *time.Location var err error // 如果没有指定时区,使用UTC if timezone == "" { loc = time.UTC } else { // 加载指定时区 loc, err = time.LoadLocation(timezone) if err != nil { return 0, fmt.Errorf("invalid timezone: %v", err) } } // 获取当前时间并转换到指定时区 now := time.Now().In(loc) // 应用日期偏移 if offset != 0 { now = now.AddDate(0, 0, offset) } // 获取当天0点时间 zero := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc) return zero.Unix(), nil } // GetDateStr 获取指定时区的日期字符串 // timezone: 时区字符串,如:"Asia/Shanghai","America/New_York",留空则使用UTC // offset: 日期偏移,0表示今天,-1表示昨天,1表示明天,以此类推 // 返回格式:"2006-01-02" func GetDateStr(timezone string, offset int) (string, error) { var loc *time.Location var err error // 如果没有指定时区,使用UTC if timezone == "" { loc = time.UTC } else { // 加载指定时区 loc, err = time.LoadLocation(timezone) if err != nil { return "", fmt.Errorf("invalid timezone: %v", err) } } // 获取当前时间并转换到指定时区 now := time.Now().In(loc) // 应用日期偏移 if offset != 0 { now = now.AddDate(0, 0, offset) } // 格式化日期 return now.Format("2006-01-02"), nil }