time.go 2.0 KB

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