当前位置:网站首页>Golang gets the start timestamp and end timestamp of a past or future week or month

Golang gets the start timestamp and end timestamp of a past or future week or month

2022-06-24 01:12:00 User 6786882

Golang Get the start timestamp and end timestamp of the past or future week and month

	 During the development process, we often need to get the start and end timestamps of a week or a month in the future relative to the current time , The corresponding methods are prepared for you .

1. Get the start and end timestamp of a week

//  Get the start and end times of a week ,week by 0 This week, ,-1 Last week, ,1 Next week and so on 
func WeekIntervalTime(week int) (startTime, endTime string) {
   now := time.Now()
   offset := int(time.Monday - now.Weekday())
   // Make a special judgment on Sunday   because time.Monday = 0
   if offset > 0 {
      offset = -6
   }

   year, month, day := now.Date()
   thisWeek := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
   startTime = thisWeek.AddDate(0, 0, offset+7*week).Format("2006-01-02") + " 00:00:00"
   endTime = thisWeek.AddDate(0, 0, offset+6+7*week).Format("2006-01-02") + " 23:59:59"

   return startTime,endTime
}

2. Get the start or end timestamp of a month

//  Get the start and end time of a month mon by 0 This month, ,-1 Last month, ,1 And so on next month 
func MonthIntervalTime(mon int) (startTime, endTime string) {
	year, month, _ := time.Now().Date()
	thisMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)
	startTime = thisMonth.AddDate(0, mon, 0).Format("2006-01-02") + " 00:00:00"
	endTime = thisMonth.AddDate(0, mon+1, -1).Format("2006-01-02") + " 23:59:59"
	return startTime,endTime
}
原网站

版权声明
本文为[User 6786882]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211119185045572K.html