2020年5月12日转时间戳
代码如下
package main
import (
"fmt"
"strings"
"time"
)
func dateToTimestamp() (dateTimestamp int64) {
date := "2020年5月12日"
date = strings.Replace(date, "年", "-", 1)
date = strings.Replace(date, "月", "-", 1)
date = strings.Trim(date, "日")
stamp, _ := time.ParseInLocation("2006-1-2", date, time.Local)
dateTimestamp = stamp.Unix()
return dateTimestamp
}
func main() {
fmt.Println(dateToTimestamp())
}
输出结果:1589212800
time.Time格式转时间戳
package main
import(
"fmt"
"time"
)
func main() {
datetime := "2015-01-01 00:00:00" //待转化为时间戳的字符串
//日期转化为时间戳
timeLayout := "2006-01-02 15:04:05" //转化所需模板
loc, _ := time.LoadLocation("Local") //获取时区
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
timestamp := tmp.Unix() //转化为时间戳 类型是int64
fmt.Println(timestamp)
//时间戳转化为日期
datetime = time.Unix(timestamp, 0).Format(timeLayout)
fmt.Println(datetime)
}