time.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package utils
  2. import "time"
  3. // 获取今天的日期(零点零分零秒)
  4. func Today() time.Time {
  5. now := time.Now()
  6. return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
  7. }
  8. // 获取明天的日期(零点零分零秒)
  9. func Tomorrow() time.Time {
  10. return Today().AddDate(0, 0, 1)
  11. }
  12. // 获取最近7天的日期范围
  13. func Last7Days() (time.Time, time.Time) {
  14. today := Today()
  15. return today.AddDate(0, 0, -6), today.Add(time.Hour * 23).Add(time.Minute * 59).Add(time.Second * 59)
  16. }
  17. // 获取上周的日期范围
  18. func LastWeek() (time.Time, time.Time) {
  19. start := Today().AddDate(0, 0, -7)
  20. end := start.AddDate(0, 0, 6).Add(time.Hour * 23).Add(time.Minute * 59).Add(time.Second * 59)
  21. return start, end
  22. }
  23. // 获取本周的日期范围
  24. func ThisWeek() (time.Time, time.Time) {
  25. start := Today().Round(0).Local().AddDate(0, 0, 0-int(time.Now().Weekday())+1) // 0是本周的第一天,+1是因为AddDate是相对于当前时间的
  26. end := start.AddDate(0, 0, 6).Add(time.Hour * 23).Add(time.Minute * 59).Add(time.Second * 59)
  27. return start, end
  28. }
  29. // 获取下周的日期范围
  30. func NextWeek() (time.Time, time.Time) {
  31. _, thisEnd := ThisWeek()
  32. start := thisEnd.AddDate(0, 0, 1)
  33. end := start.AddDate(0, 0, 6).Add(time.Hour * 23).Add(time.Minute * 59).Add(time.Second * 59)
  34. return start, end
  35. }
  36. // 获取上月的日期范围
  37. func LastMonth() (time.Time, time.Time) {
  38. today := time.Now()
  39. year, month, _ := today.Date()
  40. start := time.Date(year, month-1, 1, 0, 0, 0, 0, today.Location())
  41. end := time.Date(year, month, 0, 23, 59, 59, 999999999, today.Location())
  42. return start, end
  43. }
  44. // 获取本月的日期范围
  45. func ThisMonth() (time.Time, time.Time) {
  46. today := time.Now()
  47. year, month, _ := today.Date()
  48. start := time.Date(year, month, 1, 0, 0, 0, 0, today.Location())
  49. end := time.Date(year, month+1, 0, 23, 59, 59, 999999999, today.Location())
  50. return start, end
  51. }
  52. // 获取下月的日期范围
  53. func NextMonth() (time.Time, time.Time) {
  54. now := time.Now()
  55. year, month, _ := now.Date()
  56. nextMonth := month + 1
  57. if nextMonth > 12 {
  58. nextMonth = 1
  59. year++
  60. }
  61. startOfNextMonth := time.Date(year, nextMonth, 1, 0, 0, 0, 0, now.Location())
  62. endOfNextMonth := startOfNextMonth.AddDate(0, 1, -1).Add(time.Hour*23 + time.Minute*59 + time.Second*59)
  63. return startOfNextMonth, endOfNextMonth
  64. }