golang生成12个月

golang生成12个月_第1张图片

// GetMonthTimeCycle 获取月份周期
// 参数 year 年份
func GetMonthTimeCycle(year int) (*[]TimeCycle, error) {
	var yearstart time.Time

	var start time.Time
	var end time.Time
	var no int
	var name string
	var loc, err = time.LoadLocation("Local")
	if err != nil {
		return nil, err
	}
	yearstart, err = time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%d", year)+"-01-01 00:00:00", loc)
	if err != nil {
		return nil, err
	}

	var timeCycles []TimeCycle
	for i := 0; i <= 11; i++ {
		start = yearstart.AddDate(0, i, 0)
		end, err = time.ParseInLocation("2006-01-02 15:04:05", start.AddDate(0, 1, -1).Format("2006-01-02")+" 23:59:59", loc) //加一月 减一天得到月尾
		if err != nil {
			return nil, err
		}
		no, _ = strconv.Atoi(start.Format("200601"))
		name = fmt.Sprintf("%d年%d月", start.Year(), start.Month())
		timeCycles = append(timeCycles, TimeCycle{
			No:        no,
			Name:      name,
			StartTime: start,
			EndTime:   end,
		})
	}
	return &timeCycles, nil
}

你可能感兴趣的:(golang)