Golang 实现strtotime 字符串转换为时间戳的方法
在php中,有strtotime 将字符串转换为时间戳,在Golang 中,同样可以实现类型的函数。
package main import ( "fmt" "time" "regexp" "strings" "strconv" ) func StartTimer(name string) func(){ t := time.Now() fmt.Println(name, "started") return func(){ d := time.Now().Sub(t) fmt.Println(name, "took", d) } } func RunTimer(){ stop := StartTimer("run timer") defer stop() time.Sleep(1 * time.Second) } func strtotime(str string) int64 { uintToSeconds := map[string]int64{"minute" : 60, "hour" : 3600, "day" : 86400, "week" : 604800, "year" : ((365 * 86400) + 86400)} accumulator := time.Now().Unix() var delta int64 plus := true str = strings.TrimSpace(str) t := time.Now() if strings.Index(str, "today") >= 0 || strings.Index(str, "this month") >= 0 || strings.Index(str, "midnight") >= 0 { accumulator -= int64(t.Second()) accumulator -= int64(t.Minute()) * uintToSeconds["minute"] accumulator -= int64(t.Hour()) * uintToSeconds["hour"] } if strings.Index(str, "yesterday") >= 0 { str = "-1 day" } if strings.Index(str, "this month") >= 0 { str = "-" + strconv.Itoa(t.Day()-1) + " days" } if strings.HasPrefix(str, "in ") { str = strings.Replace(str, "in ", "", 1) } if strings.Index(str, " ago") > 0 { str = strings.Replace(str, " ago", "", 1) plus = false } if strings.Index(str, "+") >= 0 { str = strings.Replace(str, "+", "", 1) } if strings.Index(str, "-") >= 0 { str = strings.Replace(str, "-", "", 1) plus = false } noteValMap := make(map[string]int64, 10) re := regexp.MustCompile(`\d+\s+(minute|hour|day|week|year)`) parts := re.FindAllStringSubmatch(str, -1) for i, _ := range parts { strArray := strings.Split(parts[i][0], " ") v, _:= strconv.Atoi(strArray[0]) noteValMap[parts[i][1]] = int64(v) } delta = 0 for k, v := range noteValMap { delta += uintToSeconds[k] * v } if plus { accumulator += delta } else { accumulator -= delta } return accumulator } func main(){ fmt.Println("in main") timeStr := [...]string{"today", "yesterday midnight", "this month", "-1 week 3 days 30 minute", " 10 weeks 2 hours ago ", "+ 1 year 11 days 10 minutes"} for _, v := range timeStr { ts := strtotime(v) timeObj := time.Unix(ts, 10) fmt.Println(timeObj.Format("2006-01-02 15:04:05")) } RunTimer() }
output:
2022-09-28 00:00:00
2022-09-27 00:00:00
2022-09-01 00:00:00
2022-09-18 18:08:01
2022-07-20 16:38:01
2023-10-10 18:48:01
run timer started
run timer took 1.0024019s
浙公网安备 33010602011771号