datetime - 如何在 Go 中使用 GMT 格式获取当前日期和时间?

标签 datetime go

我正在尝试像这样获取日期和时间 2014-06-22 22:00:22 GMT+2 最好的方法是什么?

我正在尝试各种变体。最接近的是这个

time.Now().Format("2006-01-02 15:04:05 GMT+1")

我得到了很好的结果,除了 GMT - 这是错误的。我试过像这样更改模板并得到了结果:

GMT+0 => GMT+0

GMT+1 => GMT+4

但我住在格林威治标准时间+3 并且期待那个数字。 我做错了什么?

最佳答案

例如,对于莫斯科,GMT+03,

package main

import (
    "fmt"
    "time"
)

func main() {
    // Your Local time zone
    now := time.Now().Round(0)
    fmt.Println(now.UTC())
    fmt.Println(now)
    t := now.Format("2006-01-02 15:04:05 GMT-07")
    fmt.Println(t)

    // For example, use Moscow time zone (GMT+03)
    fmt.Println()
    moscow, err := time.LoadLocation("Europe/Moscow")
    if err != nil {
        panic(err)
    }
    now = time.Now().In(moscow)
    fmt.Println(now.UTC())
    fmt.Println(now)
    t = now.Format("2006-01-02 15:04:05 GMT-07")
    fmt.Println(t)
}

输出:

2019-04-19 17:24:20.582630875 +0000 UTC
2019-04-19 13:24:20.582630875 -0400 EDT
2019-04-19 13:24:20 GMT-04

2019-04-19 17:24:20.582729015 +0000 UTC
2019-04-19 20:24:20.582729015 +0300 MSK
2019-04-19 20:24:20 GMT+03

关于datetime - 如何在 Go 中使用 GMT 格式获取当前日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764500/

相关文章:

C# DateTime 到 "YYYYMMDDHHMMSS"格式

bash - 在 shell 脚本 bash 中获取结束时间

mysql - 检查 MySql 日期时间是否为空的更好方法

Php MySql 按小时排序自定义订单

Golang go-pg关系递归查询

go - 如何使用多个 negroni.Wrap()

http - 创建要通过 Google App Engine 提供的 tar 文件

types - 常数 1 被截断为整数?

php - Symfony-无效的日期时间格式 : 1292 Incorrect datetime value: '' for column 'timestamp' at row 1

go - 控制未导出的结构字段