其他分享
首页 > 其他分享> > Golang 实现strtotime 字符串转换为时间戳的方法

Golang 实现strtotime 字符串转换为时间戳的方法

作者:互联网

       

           在php中,有strtotime 将字符串转换为时间戳,在Golang 中,同样可以实现类型的函数。

   

  1 package main
  2 
  3 import (
  4       "fmt"
  5       "time"
  6       "regexp"
  7       "strings"
  8       "strconv"
  9     )
 10     
 11 func StartTimer(name string) func(){
 12    t := time.Now()
 13    fmt.Println(name, "started")
 14    
 15    return func(){
 16        d := time.Now().Sub(t)
 17        fmt.Println(name, "took", d)
 18        }
 19 }
 20 
 21 
 22 func RunTimer(){
 23    stop := StartTimer("run timer")
 24    
 25    defer stop()
 26    
 27    time.Sleep(1 * time.Second)   
 28 }
 29 
 30 
 31 func strtotime(str string) int64 {
 32     
 33     uintToSeconds := map[string]int64{"minute" : 60, "hour" : 3600, "day" : 86400, "week" : 604800, "year" : ((365 * 86400) + 86400)}
 34 
 35     accumulator := time.Now().Unix()
 36 
 37     var delta int64
 38     plus := true
 39     str = strings.TrimSpace(str)
 40     
 41     if strings.HasPrefix(str, "in ") {
 42         str = strings.Replace(str, "in ", "", 1)
 43     }
 44 
 45     if strings.Index(str, " ago") > 0 {
 46         str = strings.Replace(str, " ago", "", 1)
 47         plus = false
 48     }
 49     
 50     if strings.Index(str, "+") >= 0 {
 51         str = strings.Replace(str, "+", "", 1)
 52     }        
 53     
 54     if strings.Index(str, "-") >= 0 {
 55         str = strings.Replace(str, "-", "", 1)
 56         plus = false
 57     }    
 58 
 59     noteValMap := make(map[string]int64, 10)
 60    
 61    
 62     re := regexp.MustCompile(`\d+\s+(minute|hour|day|week|year)`)
 63     
 64     parts := re.FindAllStringSubmatch(str, -1)
 65    
 66     for i, _ := range parts {
 67         strArray := strings.Split(parts[i][0], " ")
 68         v, _:= strconv.Atoi(strArray[0])
 69         noteValMap[parts[i][1]] = int64(v)
 70     }   
 71     
 72     delta = 0
 73     for k, v := range noteValMap {
 74         
 75         delta += uintToSeconds[k] * v        
 76     }
 77 
 78     if plus {
 79         accumulator += delta
 80     } else {
 81         accumulator -= delta
 82     }        
 83 
 84     return accumulator
 85 }
 86 
 87 
 88 func main(){
 89     fmt.Println("in main")
 90     timeStr := [...]string{"-1 week 3 days  30 minute", " 10 weeks 2 hours ago ", "+ 1 year 11 days 10 minutes"}
 91     
 92     
 93     for _, v := range timeStr {
 94     
 95         ts := strtotime(v)
 96         
 97         timeObj := time.Unix(ts, 10)
 98         
 99         fmt.Println(timeObj.Format("2006-01-02 15:04:05"))    
100     }    
101     
102     RunTimer()
103 }
104 
105 //output:
106 //2022-08-30 23:15:32
107 //2022-07-01 21:45:32
108 //2023-09-21 23:55:32    

 

标签:Golang,func,fmt,strtotime,str,time,字符串,strings,string
来源: https://www.cnblogs.com/wallywl/p/16675782.html