GolangNote

Golang笔记

golang 当前时间、时间戳、时区的相互转化

Permalink

golang 当前时间、时间戳、时区的相互转化

golang time

时间转换实例

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
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)
    // 把时间戳转换为时间
    currenttime := time.Unix(timestamp+int64(offset), 0)
    // 格式化时间
    fmt.Println("Current time : ", currenttime.Format("2006-01-02 15:04:05"))
}

运行后输出:

plaintext: 输出结果
1
2
3
4
2015-08-19 03:11:07.131101183 +0000 UTC
1439953867
UTC 0
Current time :  2015-08-19 11:11:07

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

Related articles

Golang 时区时差处理方式

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

Golang quicktemplate 模版快速入门

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

Write a Comment to "golang 当前时间、时间戳、时区的相互转化"

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