package common import ( "time" ) const ( zeroDateStr = "0000-00-00 00:00:00" FromatTime_V1 = "2006-01-02 15:04:05" FromatTime_V2 = "2006-01-02" FromatTime_V3 = "15:04:05" FromatTime_V4 = "2006-01" ) // 将时间转换为时间搓 // 时间搓0为:1970年1月1日0时0分0秒,业务中只有数据库为0000-00-00 00:00:00,是一个绝对值很大的负数,小于0则直接返回0就可以。 func Time2Second(_time time.Time) int64 { sec := _time.Unix() if sec < 0 { return 0 } return sec } // 转换成标准格式的时间 func Time2StdString(_time time.Time) string { if TimeIsZero(_time) { return zeroDateStr } return _time.Format(FromatTime_V1) } // 获取昨天日期 func GetTimeYesterday() time.Time { return time.Now().AddDate(0, 0, -1) } // 将s转换成时间 func Second2Time(timestamp int64) time.Time { return time.Unix(timestamp, 0) } // 获取当前的s func GetCurrentSeconds() int64 { return time.Now().Unix() } // orm返回的时间体,时间搓是否为0,time直接判断isZero是不对的,需要转换成utc时区 func TimeIsZero(t time.Time) bool { t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) return t.IsZero() } // 获取当前时间开始的时间点,比如 2020-1-2 11:01:00 ——> 2020-1-2 00:00:00 func GetTimeStart(_time time.Time) time.Time { year, month, day := _time.Date() return time.Date(year, month, day, 0, 0, 0, 0, time.Local) } func StringStd2Time(time_ string) time.Time { res, err := time.ParseInLocation(FromatTime_V1, time_, time.Local) if err != nil { return _zero // 生成个默认的,降级 } return res } func GetTomorrow(time_ time.Time) time.Time { year, month, day := time_.Date() data := time.Date(year, month, day+1, 0, 0, 0, 0, time.Local) return data } func GetYesterday(time_ time.Time) time.Time { year, month, day := time_.Date() data := time.Date(year, month, day-1, 0, 0, 0, 0, time.Local) return data } func NewTimeWithYearAndMonthAndDay(year int, month uint8, day int) time.Time { return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local) }