特此做个记录
- 对刚刚 和 几分钟前的时间处理 默认返回当前时间
- 对几小时前返回几个小时 如果几个小时大于当前小时,那就返回上一天时间。
- 对于几天前 就是倒退几天前
/* home.php?mod=space&uid=238618 : 2023/3/30 10:10 home.php?mod=space&uid=686208 : zic home.php?mod=space&uid=267492 : time_test @Software: GoLand @blog : https://www.cnblogs.com/zichliang */ package test import ( "fmt" "regexp" "strconv" "strings" "testing" "time" ) func HoursBeforeDayBeforeFormat(arcTime string) string { arcTime = strings.TrimSpace(arcTime) timeList := [...]string{ "小时前", "分钟前", "刚刚", } t := time.Now() // 获取当前时间 currentTime := t.Format("2006-01-02 15:04:05") //获取当前格式的日期 for _, _value := range timeList { isContains := strings.Contains(arcTime, _value) if isContains { nowHour := time.Now().Format("15") pattern := regexp.MustCompile(`\d+`) afterNumber := pattern.FindString(arcTime) if afterNumber == "" { if arcTime == "刚刚" { return currentTime } else { return "请传入带有数字类型 比如:5小时前" } } if afterNumber <= nowHour { return currentTime } else if strings.Contains(arcTime, "分钟前") { return currentTime } else { beforeDay := t.AddDate(0, 0, -1) return beforeDay.Format("2006-01-02 15:04:05") } } } if strings.Contains(arcTime, "天前") { pattern := regexp.MustCompile(`\d+`) afterNumber, err := strconv.Atoi(fmt.Sprint("-", pattern.FindString(arcTime))) if err != nil { return fmt.Sprintln(arcTime, "正则提取错误") } return fmt.Sprintln(t.AddDate(0, 0, afterNumber).Format("2006-01-02 15:04:05")) } else { return arcTime } } func TestTime(T *testing.T) { formatTime := HoursBeforeDayBeforeFormat("1分钟前") fmt.Println(formatTime) } |