在用golang爬虫的时候
总会遇到 10天前 10分钟前 刚刚这种很影响我们爬取正常事件
所以我写了个方法 来格式化这种事件
package utils
import (
"fmt"
"regexp"
"strconv"
"strings"
"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
}
}
标签:isContains,arcTime,string,afterNumber,几天,几分钟,Golang,time,strings
From: https://www.cnblogs.com/zichliang/p/16815328.html