GolangNote

Golang笔记

Golang 时区时差处理方式

Permalink

个人习惯用 0 时区时间戳记录时间,可以方便转到不同时区,下面介绍 Golang 时区时差处理

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

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前(当地)时间
	t := time.Now()
	// 获取0时区时间
	t = time.Now().UTC()
	fmt.Println(t)
	// 获取当前时间戳
	timestamp := t.Unix()
	fmt.Println(timestamp)
	// 获取时区信息
	name, offset := t.Zone()
	fmt.Println(name, offset)

	// 把时间戳转换为时间
	// 格式化时间
	sample := "2006-01-02 15:04:05"
	// 服务器时区
	fmt.Println("Current time 1 : ", time.Unix(timestamp+int64(offset), 0).Format(sample))
	// 零时区
	fmt.Println("Current time 2 : ", time.Unix(timestamp, 0).UTC().Format(sample))
	// 指定时间差
	fmt.Println("Current time 3 : ", time.Unix(timestamp+8*3600, 0).UTC().Format(sample))
	// 或
	fmt.Println("Current time 4 : ", time.Unix(timestamp, int64(8*time.Hour)).UTC().Format(sample))
	// 或
	fmt.Println("Current time 5 : ", time.Unix(timestamp, 0).UTC().Add(8*time.Hour).Format(sample))
}

在中国服务器上运行结果:

plaintext: 时区时差处理结果
1
2
3
4
5
6
7
8
2018-01-11 07:44:25.625928252 +0000 UTC
1515656665
UTC 0
Current time 1 :  2018-01-11 15:44:25
Current time 2 :  2018-01-11 07:44:25
Current time 3 :  2018-01-11 15:44:25
Current time 4 :  2018-01-11 15:44:25
Current time 5 :  2018-01-11 15:44:25

在美国一个服务器上运行的结果:

plaintext: 时区时差处理结果
1
2
3
4
5
6
7
8
2018-01-11 07:45:59.470730955 +0000 UTC
1515656759
UTC 0
Current time 1 :  2018-01-11 02:45:59
Current time 2 :  2018-01-11 07:45:59
Current time 3 :  2018-01-11 15:45:59
Current time 4 :  2018-01-11 15:45:59
Current time 5 :  2018-01-11 15:45:59

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

Related articles

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang 数据库 Bolt 碎片整理

Bolt 是一个优秀、纯 Go 实现、支持 ACID 事务的嵌入式 Key/Value 数据库。但在使用过程中会有很多空间碎片。一般数据库占用的空间是元数据空间的 1.5~4 倍。Bolt 没有内置的压缩功能,需要手动压缩。...

Golang telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

Write a Comment to "Golang 时区时差处理方式"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms