如果输入日超出月份范围,则使用月份的结束日。例如,输入:
5
输出:
["2023-01-05","2023-02-05",...,"2023-12-05"]
输入:
31
["2023-01-31","2023-02-28",...,"2023-11-30","2023-12-31"]
2lpgd9681#
您可以使用以下帮助器函数将日期字符串列表规范化为您希望的格式(如果输入日超出范围,请改用月份的结束日)
func getLastDayOfMonth(t time.Time) time.Time { lastDayOfMonth := time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, -1, time.UTC) return lastDayOfMonth } func formatSlices(dates []string) []string { var formattedDates []string for _, date := range dates { dateSlice := strings.Split(date, "-") rawDate, err := time.Parse("2006-01-02", dateSlice[0]+"-"+dateSlice[1]+"-01") if err != nil { fmt.Println(err) } lastDayOfMonth := getLastDayOfMonth(rawDate) newDate := date rawDay, err := strconv.Atoi(dateSlice[2]) if err != nil { fmt.Println(err) } if lastDayOfMonth.Day() < rawDay { newDate = dateSlice[0] + "-" + dateSlice[1] + "-" + strconv.FormatInt(int64(lastDayOfMonth.Day()), 10) } formattedDates = append(formattedDates, newDate) } return formattedDates }
完整代码:https://go.dev/play/p/D_yWY76GyLh
1条答案
按热度按时间2lpgd9681#
您可以使用以下帮助器函数将日期字符串列表规范化为您希望的格式(如果输入日超出范围,请改用月份的结束日)
完整代码:https://go.dev/play/p/D_yWY76GyLh