You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Go语言获取一年中每月指定日期?超范围取月末

Go语言实现按指定日期获取全年每月对应日期(超出当月天数自动取月末)

需求说明

输入一个目标日期(如5或31),生成指定年份中每个月的对应日期:

  • 若目标日期在当月的有效天数范围内,直接取该日期
  • 若目标日期超出当月最大天数,自动取当月最后一天

实现代码

package main

import (
	"fmt"
	"time"
)

// getMonthlyDates 生成指定年份中每个月的目标日期(超出则取月末)
func getMonthlyDates(targetDay int, year int) []string {
	var dates []string
	for month := 1; month <= 12; month++ {
		// 构造当月第一天的时间对象
		firstDay := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
		// 通过下个月第一天减一天,得到当月最后一天
		lastDay := firstDay.AddDate(0, 1, -1)
		
		// 确定当月实际要取的日期
		actualDay := targetDay
		if targetDay > lastDay.Day() {
			actualDay = lastDay.Day()
		}
		
		// 格式化为YYYY-MM-DD字符串并加入结果集
		dates = append(dates, time.Date(year, time.Month(month), actualDay, 0, 0, 0, 0, time.UTC).Format("2006-01-02"))
	}
	return dates
}

func main() {
	// 测试用例1:目标日期5,年份2023
	targetDay := 5
	year := 2023
	fmt.Printf("输入%d的输出:%q\n", targetDay, getMonthlyDates(targetDay, year))

	// 测试用例2:目标日期31,年份2023
	targetDay = 31
	fmt.Printf("输入%d的输出:%q\n", targetDay, getMonthlyDates(targetDay, year))
}

关键逻辑说明

  1. 获取当月最后一天:利用AddDate(0,1,-1),给当月第一天加1个月再减1天,自动处理闰年、不同月份天数差异的问题,无需手动判断。
  2. 日期有效性判断:对比目标日期和当月最后一天的天数,若目标日超出范围则替换为月末日期。
  3. 日期格式化:Go语言的时间格式化需使用参考时间2006-01-02,这是固定的格式化模板,对应输出YYYY-MM-DD格式。

运行结果

  • 输入5时,输出:
    ["2023-01-05","2023-02-05","2023-03-05","2023-04-05","2023-05-05","2023-06-05","2023-07-05","2023-08-05","2023-09-05","2023-10-05","2023-11-05","2023-12-05"]
    
  • 输入31时,输出:
    ["2023-01-31","2023-02-28","2023-03-31","2023-04-30","2023-05-31","2023-06-30","2023-07-31","2023-08-31","2023-09-30","2023-10-31","2023-11-30","2023-12-31"]
    

内容的提问来源于stack exchange,提问作者Jerry Zhou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:35:20