time.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package common
  2. import (
  3. "time"
  4. )
  5. const (
  6. zeroDateStr = "0000-00-00 00:00:00"
  7. FromatTime_V1 = "2006-01-02 15:04:05"
  8. FromatTime_V2 = "2006-01-02"
  9. FromatTime_V3 = "15:04:05"
  10. FromatTime_V4 = "2006-01"
  11. )
  12. // 将时间转换为时间搓
  13. // 时间搓0为:1970年1月1日0时0分0秒,业务中只有数据库为0000-00-00 00:00:00,是一个绝对值很大的负数,小于0则直接返回0就可以。
  14. func Time2Second(_time time.Time) int64 {
  15. sec := _time.Unix()
  16. if sec < 0 {
  17. return 0
  18. }
  19. return sec
  20. }
  21. // 转换成标准格式的时间
  22. func Time2StdString(_time time.Time) string {
  23. if TimeIsZero(_time) {
  24. return zeroDateStr
  25. }
  26. return _time.Format(FromatTime_V1)
  27. }
  28. // 获取昨天日期
  29. func GetTimeYesterday() time.Time {
  30. return time.Now().AddDate(0, 0, -1)
  31. }
  32. // 将s转换成时间
  33. func Second2Time(timestamp int64) time.Time {
  34. return time.Unix(timestamp, 0)
  35. }
  36. // 获取当前的s
  37. func GetCurrentSeconds() int64 {
  38. return time.Now().Unix()
  39. }
  40. // orm返回的时间体,时间搓是否为0,time直接判断isZero是不对的,需要转换成utc时区
  41. func TimeIsZero(t time.Time) bool {
  42. t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC)
  43. return t.IsZero()
  44. }
  45. // 获取当前时间开始的时间点,比如 2020-1-2 11:01:00 ——> 2020-1-2 00:00:00
  46. func GetTimeStart(_time time.Time) time.Time {
  47. year, month, day := _time.Date()
  48. return time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  49. }
  50. func StringStd2Time(time_ string) time.Time {
  51. res, err := time.ParseInLocation(FromatTime_V1, time_, time.Local)
  52. if err != nil {
  53. return _zero // 生成个默认的,降级
  54. }
  55. return res
  56. }
  57. func GetTomorrow(time_ time.Time) time.Time {
  58. year, month, day := time_.Date()
  59. data := time.Date(year, month, day+1, 0, 0, 0, 0, time.Local)
  60. return data
  61. }
  62. func GetYesterday(time_ time.Time) time.Time {
  63. year, month, day := time_.Date()
  64. data := time.Date(year, month, day-1, 0, 0, 0, 0, time.Local)
  65. return data
  66. }
  67. func NewTimeWithYearAndMonthAndDay(year int, month uint8, day int) time.Time {
  68. return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local)
  69. }