## 获取当前时间戳 ``` package main import ( "fmt" "time" ) func main(){ timeUnix:=time.Now().Unix() fmt.Println(timeUnix) // 1598794757 } ``` ## 获取年月日时分秒 ``` package main import ( "fmt" "time" ) func main(){ year:=time.Now().Year() //年 month:=time.Now().Month() //月 day:=time.Now().Day() //日 hour:=time.Now().Hour() //时 minute:=time.Now().Minute() //分钟 second:=time.Now().Second() //秒 fmt.Println(year, month, day, hour, minute, second) // 2020 August 30 21 49 10 } ``` ## 当前时间格式化 ``` package main import ( "fmt" "time" ) func main(){ timeStr:=time.Now().Format("2006-01-02 15:04:05") // 2006-01-02 15:04:05据说是golang的诞生时间,固定写法 fmt.Println(timeStr) // 2020-08-30 21:40:30 } ``` ## 时间戳格式化 ``` package main import ( "fmt" "time" ) func main(){ timeUnix:=time.Now().Unix() formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05") fmt.Println(formatTimeStr) // 2020-08-30 21:42:13 } ``` ## 格式化时间转时间戳 ``` package main import ( "fmt" "time" ) func main(){ formatTime, err := time.ParseInLocation("2006-01-02 15:04:05", "2020-02-02 20:20:20", time.Local) if err == nil{ timeUnix := formatTime.Unix() fmt.Println(timeUnix) // 1580674820 } } ```