time.Now().Unix()t.Formattime.Parse

golang timestamp time 时间戳小结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
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

本文网址: https://pylist.com/topic/110.html 转摘请注明来源