简体   繁体   English

Go 语言 time.Parse() 用于没有时区的时间戳

[英]Go language time.Parse() for timestamps with no timezone

In Go I'm trying to use the time.Parse() function from the time package to convert a string timestamp into a Time object.在 Go 中,我尝试使用time包中的time.Parse()函数将字符串时间戳转换为Time对象。 I know Go has an uncommon way of representing the time format your timestamps are in by providing it with an example of how their reference time ( Mon Jan 2 15:04:05 -0700 MST 2006 ) would be displayed in your format.我知道 Go 有一种不常见的方式来表示时间戳所采用的时间格式,方法是向它提供一个示例,说明它们的参考时间( Mon Jan 2 15:04:05 -0700 MST 2006 )将如何以您的格式显示。 I'm still having issues with errors however.但是,我仍然遇到错误问题。 Here is an example of one of my timestamps:这是我的时间戳之一的示例:

Tue Nov 27 09:09:29 UTC 2012

Here is what the call I'm making looks like:这是我正在拨打的电话的样子:

    t, err := time.Parse("Mon Jan 02 22:04:05 UTC 2006", "Tue Nov 27 09:09:29 UTC 2012")

So basically what I've done here is try and match the formatting for day name/month name/day number, the hour/minute/second format, the string literal "UTC" and the year format.所以基本上我在这里所做的是尝试匹配日期名称/月份名称/日期编号、小时/分钟/秒格式、字符串文字“UTC”和年份格式的格式。 Note that I've increased the hours field of the Go reference format by 7 (from 15 to 22 ) to account for the fact that their timestamp is in a negative 7 timezone and all my timestamps are in a UTC timezone.请注意,我已将 Go 参考格式的 hours 字段增加7 (从1522 ),以说明它们的时间戳在负 7 时区并且我所有的时间戳都在 UTC 时区的事实。

The error I get is:我得到的错误是:

parsing time "Tue Nov 27 09:09:29 UTC 2012" as "Mon Jan 02 22:04:05 UTC 2006": cannot parse ":09:29 UTC 2012" as "2"

What am I doing wrong here?我在这里做错了什么? Am I misinterpreting how to use time.Parse() or is my use case not supported for some reason?我是否误解了如何使用time.Parse()或者我的用例由于某种原因不受支持?

You're format string should be:你的格式字符串应该是:

Mon Jan 02 15:04:05 MST 2006

playground游乐场

That is, use MST for the timezone, and 15 for the hour, as documented in your linked Parse function.也就是说,时区使用MST ,小时使用15 ,如链接的 Parse 函数中所述。

In this case, you can use time.UnixDate :在这种情况下,您可以使用time.UnixDate

package main

import (
   "fmt"
   "time"
)

func main() {
   t, e := time.Parse(time.UnixDate, "Tue Nov 27 09:09:29 UTC 2012")
   if e != nil {
      panic(e)
   }
   fmt.Println(t)
}

https://golang.org/pkg/time#UnixDate https://golang.org/pkg/time#UnixDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM