package utime import ( "github.com/jinzhu/now" "time" ) const ( Day = 86400 Layout = "2006-01-02 15:04:05" LayoutDay = "2006-01-02" LayoutDay2 = "20060102" LayoutMonth = "2006-01" LayoutMinute = "2006-01-02 15:04" ) // 获取时间所在周的第一天(周一) 00:00:00,和最后一天(周日)23:59:59 func WeekStartEnd(date time.Time) (start, end time.Time) { w := 0 week := date.Weekday() if week == time.Sunday { w = 7 } else { w = int(week) } startTmp := date.AddDate(0, 0, -w+1) endTmp := date.AddDate(0, 0, 7-w) start = time.Date(startTmp.Year(), startTmp.Month(), startTmp.Day(), 0, 0, 0, 0, startTmp.Location()) end = time.Date(endTmp.Year(), endTmp.Month(), endTmp.Day(), 23, 59, 59, 999, endTmp.Location()) return } // 当天开始结束 func DayStartEnd(date time.Time) (start, end time.Time) { start = time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location()) end = time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 999, date.Location()) return } // 获取时间所在月的第一天(1号) 00:00:00,和最后一天23:59:59 func MonthStartEnd(date time.Time) (start, end time.Time) { start = time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location()) lastDay := now.New(start).EndOfMonth().Day() end = time.Date(date.Year(), date.Month(), lastDay, 23, 59, 59, 999999999, date.Location()) return } // 增加年/月 // 因为golang原生的Time.AddDate增加月份的时候有bug func AddDate(t time.Time, years int, months int) time.Time { year, month, day := t.Date() hour, min, sec := t.Clock() // firstDayOfMonthAfterAddDate: years 年,months 月后的 那个月份的1号 firstDayOfMonthAfterAddDate := time.Date(year+years, month+time.Month(months), 1, hour, min, sec, t.Nanosecond(), t.Location()) // firstDayOfMonthAfterAddDate 月份的最后一天 lastDay := now.New(firstDayOfMonthAfterAddDate).EndOfMonth().Day() // 如果 t 的天 > lastDay,则设置为lastDay // 如:t 为 2020-03-31 12:00:00 +0800,增加1个月,为4月31号 // 但是4月没有31号,则设置为4月最后一天lastDay(30号) if day > lastDay { day = lastDay } return time.Date(year+years, month+time.Month(months), day, hour, min, sec, t.Nanosecond(), t.Location()) }