unix时间戳转换


参考:https://blog.csdn.net/feiwutudou/article/details/81001453

package main
import (
   "time"
   "fmt"
)
func main() {
   //获取当前时间
   t := time.Now() //2018-07-11 15:07:51.8858085 +0800 CST m=+0.004000001
   fmt.Println(t)
   //获取当前时间戳
   fmt.Println(t.Unix()) //1531293019
   //获得当前的时间
   fmt.Println(t.Uninx().Format("2006-01-02 15:04:05"))  //2018-7-15 15:23:00
   //时间 to 时间戳
   loc, _ := time.LoadLocation("Asia/Shanghai")        //设置时区
   tt, _ := time.ParseInLocation("2006-01-02 15:04:05", "2018-07-11 15:07:51", loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
   fmt.Println(tt.Unix())                             //1531292871
   //时间戳 to 时间
   tm := time.Unix(1531293019, 0)
   fmt.Println(tm.Format("2006-01-02 15:04:05")) //2018-07-11 15:10:19
   //获取当前年月日,时分秒
   y := t.Year()                 //年
   m := t.Month()                //月
   d := t.Day()                  //日
   h := t.Hour()                 //小时
   i := t.Minute()               //分钟
   s := t.Second()               //秒
   fmt.Println(y, m, d, h, i, s) //2018 July 11 15 24 59
}

字符串转时间

stringTime := "2017-08-30 16:40:41"
loc, _ := time.LoadLocation("Local")
the_time, err := time.ParseInLocation("2006-01-02 15:04:05", stringTime, loc)
if err == nil {
	unix_time := the_time.Unix() //1504082441
	fmt.Println(unix_time)
}

文章作者: 小游
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小游 !
  目录