Go语言-时间处理

摘要

Go处理时间

Go时间处理

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//以YY-mm-dd HH:MM:SS.9位 输出当前时间:
func main() {
fmt.Println(time.Now())
}
output:
2017-02-27 01:20:00.567634365 +0800 CST

//获取时间戳:
func main() {
fmt.Println(time.Now().Unix())
}

output:

//给定一个时间戳,返回一个标准datetime时间:
func main() {
timestamp := time.Now().Unix()
fmt.Println(time.Unix(timestamp, 0))
}

output:
2017-02-27 01:18:07 +0800 CST

//指定一个时间:
func main() {
fmt.Println(time.Date(2017, 02, 27, 20, 20, 20, 20, time.Local))
}

output:
2017-02-27 20:20:20.00000002 +0800 CST

> Date初始化的时候最后一个参数,传的是一个地区struct,可以直接引用time包给我提供现成的utc时区,也可以用local本地计算机的。由于直接给了nsec参数


//格式化时间:
x := time.Date(2017, 02, 27, 17, 30, 20, 20, time.Local)
fmt.Println(x.Format("2006-01-02 15:04:05"))

output:
2017-02-27 17:30:20

//字符串转时间戳:
func main() {
x := "2017-02-27 17:30:20"
p, _ := time.Parse("2006-01-02 15:04:05", x)
fmt.Println(p.Unix())
}

output:

//字符串转时间(其实使用time.Parse转回来就是和字符串相同的格式了)
func main() {
x := "2017-02-27 17:30:20"
p, _ := time.Parse("2006-01-02 15:04:05", x)
fmt.Println(p)
}

output:
2017-02-27 17:30:20 +0000 UTC

时间函数

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"time"

)


func main(){
//【时间获取及格式化】
//获取当前时间
now_time := time.Now()
fmt.Printf("Now_time=%v,数据类型:%T", now_time, now_time)


//通过now获取年月日时分秒
fmt.Printf("年=%v\n", now_time.Year())
fmt.Printf("月=%v\n", now_time.Month()) //默认是英文的月份
fmt.Printf("月=%v\n", int(now_time.Month())) //加int转换为数字
fmt.Printf("日=%v\n", now_time.Day())
fmt.Printf("时=%v\n", now_time.Hour())
fmt.Printf("分=%v\n", now_time.Minute())
fmt.Printf("秒=%v\n", now_time.Second())



//格式化日期时间①
fmt.Printf("当前时间 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second())

//把格式化好的时间返回给一个变量,然后输出
date_now := fmt.Sprintf("当前时间 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second())
fmt.Printf("date:%v\n", date_now)


//格式化日期时间②
//2006/01/02 15:04:05 这里必须数字一个不差的写
//据说是因为golang设计者在这个时间有设计golang的想法
fmt.Printf(now_time.Format("2006/01/02 15:04:05\n"))
fmt.Printf(now_time.Format("2006/01/02\n"))
fmt.Printf(now_time.Format("15:04:05\n"))



//【时间常量应用】
//时间单位换算
// const {
// Nanosecond Duration = 1 //纳秒
// Microsecond = 1000 * Nanosecond //微秒
// Millisecond = 1000 * Microsecond //毫秒
// Second = 1000 * Millisecond //秒
// Minute = 60 * Second //分钟
// Hour = 60 * Minute //小时
// }


//每隔1秒输出一个数字,到100停止
i := 0
for {
i++
fmt.Println(i)
//休眠
time.Sleep(time.Second)
if i == 100 {
break
}
}

//每隔0.1秒输出一个数字,到100停止
i := 0
for {
i++
fmt.Println(i)
//休眠
//这里不能用time.Second *0.1,会有异常
time.Sleep(time.Millisecond * 100)
if i == 100 {
break
}
}


//获取当前时间戳还有纳秒时间戳,相当于php中的time和microtime
fmt.Printf("unix时间戳=%v,unix纳秒时间戳=%v", now_time.Unix(), now_time.UnixNano())

}

时间戳

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"strconv"
"time"
)

func main() {
t := time.Now()
fmt.Println(t)

fmt.Println(t.UTC().Format(time.UnixDate))

fmt.Println(t.Unix())

timestamp := strconv.FormatInt(t.UTC().UnixNano(), 10)
fmt.Println(timestamp)
timestamp = timestamp[:10]
fmt.Println(timestamp)
}

时间格式化字符串转换

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
package main

import (
"fmt"
"strconv"
"time"
)

func main() {
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.Parse(longForm, "Jun 21, 2017 at 0:00am (PST)")
fmt.Println(t)

const shortForm = "2006-Jan-02"
t, _ = time.Parse(shortForm, "2017-Jun-21")
fmt.Println(t)

t, _ = time.Parse("01/02/2006", "06/21/2017")
fmt.Println(t)
fmt.Println(t.Unix())

i, err := strconv.ParseInt("1498003200", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm)

var timestamp int64 = 1498003200
tm2 := time.Unix(timestamp, 0)
fmt.Println(tm2.Format("2006-01-02 03:04:05 PM"))
fmt.Println(tm2.Format("02/01/2006 15:04:05 PM"))
}
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
"fmt"
"strings"
"time"
)

func main() {

var dates [4]time.Time

dates[0], _ = time.Parse("2006-01-02 15:04:05.000000000 MST -07:00", "1609-09-12 19:02:35.123456789 PDT +03:00")
dates[1], _ = time.Parse("2006-01-02 03:04:05 PM -0700", "1995-11-07 04:29:43 AM -0209")
dates[2], _ = time.Parse("PM -0700 01/02/2006 03:04:05", "AM -0209 11/07/1995 04:29:43")
dates[3], _ = time.Parse("Time:Z07:00T15:04:05 Date:2006-01-02 ", "Time:-03:30T19:18:35 Date:2119-10-29")

defaultFormat := "2006-01-02 15:04:05 PM -07:00 Jan Mon MST"

formats := []map[string]string{
{"format": "2006", "description": "Year"},
{"format": "06", "description": "Year"},

{"format": "01", "description": "Month"},
{"format": "1", "description": "Month"},
{"format": "Jan", "description": "Month"},
{"format": "January", "description": "Month"},

{"format": "02", "description": "Day"},
{"format": "2", "description": "Day"},

{"format": "Mon", "description": "Week day"},
{"format": "Monday", "description": "Week day"},

{"format": "03", "description": "Hours"},
{"format": "3", "description": "Hours"},
{"format": "15", "description": "Hours"},

{"format": "04", "description": "Minutes"},
{"format": "4", "description": "Minutes"},

{"format": "05", "description": "Seconds"},
{"format": "5", "description": "Seconds"},

{"format": "PM", "description": "AM or PM"},

{"format": ".000", "description": "Miliseconds"},
{"format": ".000000", "description": "Microseconds"},
{"format": ".000000000", "description": "Nanoseconds"},

{"format": "-0700", "description": "Timezone offset"},
{"format": "-07:00", "description": "Timezone offset"},
{"format": "Z0700", "description": "Timezone offset"},
{"format": "Z07:00", "description": "Timezone offset"},

{"format": "MST", "description": "Timezone"}}

for _, date := range dates {
fmt.Printf("\n\n %s \n", date.Format(defaultFormat))
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12))
fmt.Printf("%-15s | %-12s | %12s \n", "Type", "Placeholder", "Value")
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12))

for _, f := range formats {
fmt.Printf("%-15s | %-12s | %-12s \n", f["description"], f["format"], date.Format(f["format"]))
}
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12))
}
}
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

time包的一些其他用法
time包很强大,这里不能整个篇幅的进行介绍,可以自己去看官方的文档。

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
1
time常用方法

After(u Time) bool
时间类型比较,是否在Time之后

Before(u Time) bool
时间类型比较,是否在Time之前

Equal(u Time) bool
比较两个时间是否相等

IsZero() bool
判断时间是否为零值,如果secnsec两个属性都是0的话,则该时间类型为0

Date() (year int, month Month, day int)
返回年月日,三个参数

Year() int
返回年份

Month() Month
返回月份.是Month类型

Day() int
返回多少号

Weekday() Weekday
返回星期几,是Weekday类型

ISOWeek() (year, week int)
返回年份,和该填是在这年的第几周.

Clock() (hour, min, sec int)
返回小时,分钟,秒

Hour() int
返回小时

Minute() int
返回分钟

Second() int
返回秒数

Nanosecond() int
返回纳秒

package main

import "fmt"
import "time"

func main() {
p := fmt.Println

now := time.Now()
p(now)

then := time.Date(
2017, 06, 21, 20, 34, 58, 0, time.UTC)
p(then)

p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())

p(then.Weekday())

p(then.Before(now))
p(then.After(now))
p(then.Equal(now))

diff := now.Sub(then)
p(diff)

p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds())

p(then.Add(diff))
p(then.Add(-diff))
}

Go计算运行的时间

time.Since()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"fmt"
"time"
)

func StartCac() {
t1 := time.Now() // get current time
//logic handlers
for i := 0; i < 1000; i++ {
fmt.Print("*")
}
cost := time.Since(start)
fmt.Printf("cost=[%s]",cost)
}

func main(){
StartCac()
}

defer

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
package main

import (
"fmt"
"time"
)

func sum(a ...int) int {
defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行
total := 0
for _, val := range a {
total += val
}
return total
}

func trace(msg string) func() {
start := time.Now()
fmt.Printf("enter %s\n", msg)
return func() {
fmt.Printf("exit %s (%s)\n", msg, time.Since(start))
}
}

func main() {
count := sum(3, 5, 9)
fmt.Printf("%d\n", count)
}

time.Now().Unix()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main
import (
"fmt"
"time"
"strconv"
)

//测试函数
func test_func() {
str := "" //声明一个字符串
for i := 0; i < 100000; i++ { //for循环10W次拼接
str += "golang" + strconv.Itoa(i) //整数转字符串拼接
}
}

func main(){
//测试test_func的执行时间
start := time.Now().Unix()
test_func()
end := time.Now().Unix()
fmt.Printf("执行消耗的时间为:%v秒", end - start)
}

Go Sleep

1
time.Sleep(time.Second)

匿名函数修改结果

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
package main

import (
"fmt"
"time"
)

func sum(a, b int) (result int) {
//defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行
defer func() { result += a }() //被延时执行的匿名函数甚至可以修改函数返回给调用者的返回值
result = 0
result += a
result += b
return result
}

func trace(msg string) func() {
start := time.Now()
fmt.Printf("enter %s\n", msg)
return func() {
fmt.Printf("exit %s (%s)\n", msg, time.Since(start))
}
}

func main() {
count := sum(3, 8)
fmt.Printf("%d\n", count)
}