使用time包获取指定数量年、季度、月、周边界
2022-07-25 本文已影响0人
JuMinggniMuJ
1.定义返回数据结构体:
type formatBorder struct {
Start string `json:"start"`
End string `json:"end"`
Name string `json:"name"`
}
2.获取年边界:
func yearDemo(num int) ([]formatBorder) {
res := make([]formatBorder,num)
now := time.Now()
for i :=0 ; i < num ; i++{
year := now.AddDate(-i,0,0).Year()
res[num-i-1] = formatBorder{fmt.Sprintf("%v-01-01",year), fmt.Sprintf("%v-12-31",year), fmt.Sprintf("%v年",year)}
}
return res
}
3.获取季度边界:
func quarterDemo(num int) ([]formatBorder) {
res := make([]formatBorder,num)
now := time.Now()
for i :=0 ; i < num ; i++{
local := now.AddDate(0,-3*i,0)
start , end , name , year:= "" , "" ,"" , local.Year()
switch int(local.Month()) {
case 1,2,3:
start = fmt.Sprintf("%v-01-01",year)
end = fmt.Sprintf("%v-03-31",year)
name = fmt.Sprintf("%v-Q1",year)
case 4,5,6:
start = fmt.Sprintf("%v-04-01",year)
end = fmt.Sprintf("%v-06-30",year)
name = fmt.Sprintf("%v-Q2",year)
case 7,8,9:
start = fmt.Sprintf("%v-07-01",year)
end = fmt.Sprintf("%v-09-30",year)
name = fmt.Sprintf("%v-Q3",year)
default:
start = fmt.Sprintf("%v-10-01",year)
end = fmt.Sprintf("%v-12-31",year)
name = fmt.Sprintf("%v-Q4",year)
}
res[num-i-1] = formatBorder{start,end,name}
}
return res
}
4.获取月边界:
func monthDemo(num int) ([]formatBorder){
res := make([]formatBorder,num)
dateStart ,_:= time.Parse("2006-01-02",fmt.Sprintf("%v-01",time.Now().Format("2006-01")))
for i := 0 ; i < num ; i++ {
start := dateStart.AddDate(0,-i,0).Format("2006-01-02")
end := dateStart.AddDate(0,-(i-1),-1).Format("2006-01-02")
name := fmt.Sprintf("%v年%v月",start[0:4],start[5:7])
res[num-i-1] = formatBorder{start,end,name}
}
return res
}
5.0 周边界:
func weekendBase(t time.Time) formatBorder{
start , end := "" , ""
switch int(t.Weekday()) {
case 0:
start = t.AddDate(0,0,-6).Format("2006-01-02")
end = t.Format("2006-01-02")
default:
start = t.AddDate(0,0,-int(t.Weekday())+1).Format("2006-01-02")
end = t.AddDate(0,0,7-int(t.Weekday())).Format("2006-01-02")
}
return formatBorder{start,end,"周边界"}
}
5.1 本周边界:
func thisWeekendBorder() formatBorder{
return weekendBase(time.Now())
}
5.2 上周边界:
func preWeekendBorder() formatBorder{
return weekendBase(time.Now().AddDate(0,0,-7))
}
5.3 下周边界:
func nextWeekendBorder() formatBorder{
return weekendBase(time.Now().AddDate(0,0,7))
}