简体   繁体   中英

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. 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. 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. 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.

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?

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.

In this case, you can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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