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 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

Golang sync.WaitGroup 的 Wait 超时处理

sync.WaitGroup 使用 `Add(1)`、`Done()`、`Wait()`组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。...

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

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