package repositories import ( "fmt" "time" ) // FormatTimeFlexible 灵活格式化时间字符串 // 支持输入格式: "2006", "2006-01", "2006-01-02" // 输出格式按照指定的格式进行输出 func (r *UserRepository) FormatTimeFlexible(timeStr string, outputFormat string) (string, error) { // 修正:使用正确的格式模板 inputFormats := []string{ "2006-01-02", // 年-月-日(正确格式) "2006-01", // 年-月 "2006", // 年 } var parsedTime time.Time var err error // 尝试解析不同格式 for _, format := range inputFormats { parsedTime, err = time.Parse(format, timeStr) if err == nil { break } } if err != nil { return "", fmt.Errorf("无法解析时间字符串 '%s'", timeStr) } return parsedTime.Format(outputFormat), nil }