go - 解析时间戳字符串时出现错误

标签 go

我尝试解析

Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)



但是出现了以下错误

parsing time "Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)" as "2006-01-02T15:04:05Z07:00": cannot parse "Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)" as "2006" 0001-01-01 00:00:00 +0000 UTC



从前端我可以根据位置或区域获取任何格式的时间戳。但是,在go lang中,我试图解析任何时间戳并将其转换为UTC以存储在分类帐中。处理这种情况的正确方法是什么?
t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

最佳答案

Go时间布局中使用的引用时间是特定时间Mon Jan 2 15:04:05 MST 2006。要定义自己的格式,请记下引用时间的格式。

由于MSTGMT-0700,因此在第一个参数中使用引用字符串。

package main

import (
    "fmt"
    "time"
)

func main() {

    // Parsing your custom time format by using the reference time in your format.
    t1, err := time.Parse(
             "Mon Jan 02 2006 15:04:05 GMT-0700",
             "Tue Apr 07 2020 11:17:47 GMT+0530")

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(t1.UTC())
}

The Go Playground

关于go - 解析时间戳字符串时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61073647/

相关文章:

包含一组加载一次的数据的 Go 包

ruby - Golang 中 Ruby 的 "methods"方法的等价物是什么?

google-app-engine - 使用 Go 在 Google App Engine 中读取本地文件

go - 如何在 Go 中将方法作为参数传递?

Golang 多个收件人与 gomail.v2

unit-testing - 在单元测试中模拟 context.Done()

golang zlib 阅读器输出未被复制到标准输出

pointers - 将结构指针转换为接口(interface){}

json - 将一对多关系检索到 JSON sql pure、Golang、Performance

go - Jmoiron SQLX Golang通用接口(interface)