1. 获取当前时间字符串(北京时间)
import "time"
// "2023-05-29 15:10:41"
func GetNowStr() string {
loc, _ := time.LoadLocation("Asia/Shanghai")
return time.Now().In(loc).Format("2006-01-02 15:04:05")
}
2. 时间戳转时间字符串(北京时间)
import "time"
func TransTimestampToStr(Timestamp int64) string {
timeLayout := "2006-01-02 15:04:05"
loc, _ := time.LoadLocation("Asia/Shanghai")
timeStr := time.Unix(Timestamp, 0).In(loc).Format(timeLayout)
return timeStr
}
3. 时间字符串转时间戳(北京时间)
import "time"
func TransTimeStrToStamp(timeStr string) (formatTime time.Time, err error) {
if len(timeStr) == 10 {
timeStr += " 00:00:00"
loc, _ := time.LoadLocation("Asia/Shanghai")
formatTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
return formatTime, err
} else if len(timeStr) == 19 {
loc, _ := time.LoadLocation("Asia/Shanghai")
formatTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
return formatTime, err
}
return formatTime, errors.New("timeStr format error")
}
rTime, err := TransTimeStrToStamp(timeStr)
if err != nil {
return ""
}
rTimestamp := rTime.Unix()
4. 过去时间(timeStr)距离现在差几天
// 计算相差天数
func CalcTime(timeStr string) string {
nowTimestamp := time.Now().Unix()
recordTime, err := TransTimeStrToStamp(timeStr)
if err != nil {
return ""
}
recordTimestamp := recordTime.Unix()
timeDiff := int(math.Ceil(float64(nowTimestamp-recordTimestamp) / 86400))
if timeDiff > 0 {
return fmt.Sprintf("已超时%d天", timeDiff)
}
return ""
}