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 quicktemplate 模版快速入门

Golang 有很多的模版引擎,自带的 `html/template` 也很好,大多数情况都能满足需求,只是有些逻辑、条件判断不好在模版里实现, `quicktemplate` 是个很好的选择。...

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

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

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

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