golang timestamp time 时间戳小结

golang 获取时间戳用time.Now().Unix(),格式化时间用t.Format,解析时间用time.Parse

package main

import (
	"fmt"
	"time"
)

func main() {
	// t := time.Now().UTC() //获取当前UTC时间的结构体
	// t := time.Now().UTC().Add(8 * time.Hour) // 第8时区
	t := time.Now() //获取当前时间的结构体

	secs := t.Unix()          // 秒
	nanos := t.UnixNano()     // 纳秒
	millis := nanos / 1000000 // 毫秒

	fmt.Println(t)
	fmt.Println(t.UTC())
	fmt.Println(t.UTC().Add(8 * time.Hour))
	fmt.Println(secs)
	fmt.Println(millis)
	fmt.Println(nanos)

	fmt.Println(t.Format("2006-01-02 15:04:05")) //格式化输出

	//获取时间戳
	timestamp := time.Now().Unix()
	fmt.Println(timestamp)

	//格式化为字符串,tm为Time类型
	tm := time.Unix(timestamp, 0)
	fmt.Println(tm.Format("2006-01-02 03:04:05 PM"))
	fmt.Println(tm.Format("02/01/2006 15:04:05 PM"))

	//从字符串转为时间戳,第一个参数是格式,第二个是要转换的时间字符串
	tm2, _ := time.Parse("01/02/2006", "02/08/2015")
	fmt.Println(tm2.Unix())

	fmt.Println(time.Now().Format(time.RFC850))
	// Wednesday, 05-Aug-15 18:16:13 CST
}

输出:

2016-09-01 10:01:29.649914422 +0800 CST
2016-09-01 02:01:29.649914422 +0000 UTC
2016-09-01 10:01:29.649914422 +0000 UTC
1472695289
1472695289649
1472695289649914422
2016-09-01 10:01:29
1472695289
2016-09-01 10:01:29 AM
01/09/2016 10:01:29 AM
1423353600
Thursday, 01-Sep-16 10:01:29 CST
Relative Articles