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 http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Golang WebAssembly 了解一下

Go 1.11 起开始支持 WebAssembly ,也就是说以后可以使用任何语言作为“前端语言”来进行 Web 开发。...

谷歌翻译的 golang 库推荐

Google 的翻译越来越好了,官方的Golang SDK 已经很完美,这里介绍的是几个非官方发布的有特色的库。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms