Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

datetime

go

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?

like image 975
Bryce Thomas Avatar asked Dec 18 '13 08:12

Bryce Thomas


People also ask

How do you parse time in go?

We can parse any time by using time. Parse function which takes our time string and format in which our string is written as input and if there is no error in our format, it will return a Golang time object.

What is the format of time time in Golang?

Golang Time Format YYYY-MM-DD Time instance into a standard string in the YYYY-MM-DD format.

How do I print a date on go?

In Go, the current time can be determined by using time. Now(), provided by the time package. Package time provides functionality for measuring and displaying the time. To print Current date-time you need to import the “time” package in your Go program to work with date and time.


1 Answers

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

like image 151
mjibson Avatar answered Sep 22 '22 20:09

mjibson