Golang获取过去或将来某周某月的开始时间戳和结束时间戳

本文介绍了一种在Golang中获取相对当前时间过去或将来的某周某月的开始和结束时间戳的方法,并提供了具体实现代码。

Golang获取过去或将来某周某月的开始时间戳和结束时间戳

​ 开发过程中我们经常需要拿到相对于当前时间过去或将来的某周某月的开始和结束时间戳,下面为大家准备了对应的方法。

1.获取某周的开始和结束时间戳

// 获取某周的开始和结束时间,week为0本周,-1上周,1下周以此类推
func WeekIntervalTime(week int) (startTime, endTime string) {
   now := time.Now()
   offset := int(time.Monday - now.Weekday())
   //周日做特殊判断 因为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.获取某月的开始或结束时间戳

// 获取某月的开始和结束时间mon为0本月,-1上月,1下月以此类推
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
}
// 将格式化时间转时间戳
func DateToTm(date string) time.Time {
   var cstSh, _ = time.LoadLocation("Asia/Shanghai")
   tm, _ := time.ParseInLocation("2006-01-02 15:04:05", date, cstSh)
   return tm
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值