// GetWeekTimeCycleForGBT74082005 获取星期周期 中华人民共和国国家标准 GB/T 7408-2005
// 参数 year 年份 GB/T 7408-2005
func GetWeekTimeCycleForGBT74082005(year int) (*[]TimeCycle, error) {var yearstart time.Time //当年最开始一天var yearend time.Time //当年最后一天var yearstartweek int //当年第一年周几var yearendweek int //当年最后一天周几var start time.Time //周期开始时间var end time.Time //周期结束时间var no int //yyyy0001var name string //名称 xxxx年xxxx周var week int //第几周var spanyear = true //默认能跨年var timeCycles []TimeCyclevar 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}yearend, err = time.ParseInLocation("2006-01-02 15:04:05", yearstart.AddDate(1, 0, -1).Format("2006-01-02")+" 23:59:59", loc) //加一年 减一天得到if err != nil {return nil, err}// Sunday Weekday = iota 星期天 是0yearstartweek = int(yearstart.Weekday()) //1月1号是星期几yearendweek = int(yearend.Weekday()) //12月31号是星期几if yearendweek > 0 && yearendweek <= 3 { //如果今年的最后一天是周1到周3 说明是要被包含的 此时不应该跨年spanyear = false}var addDay = (8 - yearstartweek) % 7 //如果今天是 星期一 则无需处理 如果是0则+1 1则+0 2则+6 3则+5 4则+4 5则+3//第一周if yearstartweek == 0 || yearstartweek == 5 || yearstartweek == 6 { //当1月1号是周五 周六 或者 周日 则这几天(0-2)是属于上一年的周期yearstart = yearstart.AddDate(0, 0, addDay)} else { //否则上一年后几天(0-3)是属于这一年的yearstart = yearstart.AddDate(0, 0, -1*(yearstartweek-1))}for {start = yearstart.AddDate(0, 0, week*7)end, err = time.ParseInLocation("2006-01-02 15:04:05", start.AddDate(0, 0, 6).Format("2006-01-02")+" 23:59:59", loc) //加一周if err != nil {return nil, err}week++no, _ = strconv.Atoi(fmt.Sprintf("%d%04d", year, week))name = fmt.Sprintf("%d年%d周", year, week)if start.Year() <= year && //其实年必须在当前年(end.Year() == year || //在当前年(end.Year() >= year && spanyear)) { //不在当前年 看是否可以跨年timeCycles = append(timeCycles, TimeCycle{No: no,Name: name,StartTime: start,EndTime: end,})} else {break}}return &timeCycles, nil
}