Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC string to time object

Tags:

datetime

time

go

I have this datetime, or something that looks like it.

2014-11-17 23:02:03 +0000 UTC

I want to convert this to a time object and I've been unable to produce any output from time.Parse apart from:

0001-01-01 00:00:00 +0000 UTC

I've tried these layouts:

time.RFC3339
0001-01-01 00:00:00 0000 UTC
2016-10-10
time.UnixDate

And a few more - none have worked.

This is how I'm calling parse :

updatedAt, err := time.Parse(time.UnixDate, updatedAtVar)

How do I create a time object from a string?

like image 477
praks5432 Avatar asked Aug 05 '16 21:08

praks5432


2 Answers

Most likely you used a wrong layout, and you didn't check the returned error.

The layout must be this date/time, in the format your input time is:

Mon Jan 2 15:04:05 -0700 MST 2006

See this working code:

layout := "2006-01-02 15:04:05 -0700 MST"
t, err := time.Parse(layout, "2014-11-17 23:02:03 +0000 UTC")
fmt.Println(t, err)

Output (try it on the Go Playground):

2014-11-17 23:02:03 +0000 UTC <nil>

EDIT:

In your question you included a + sign in your input time (as part of the zone offset), but you have error with times of other formats.

Time.String() uses the following format string:

"2006-01-02 15:04:05.999999999 -0700 MST"

So either use this to parse the times, or use Time.Format() to produce your string representations where you can specify the layout, so you can use the same layout to parse the time strings.

2nd round:

You're including your time strings in URLs. The + sign is a special character in URL encoding: it denotes the space. So the + gets converted to space (and so it vanishes from your time string). Use proper URL encoding! Check out the net/url package, and this example.

like image 125
icza Avatar answered Sep 23 '22 05:09

icza


Didn't see this yet but for those that don't know the formats, time has the formats builtin as constants. so you can reference them when parsing or formating.

time.Parse(time.RFC3339, <your time.Time object here>)
<time.Time object>.Format(time.RFC3339) //or other type of formats

Here they are for reference

ANSIC       = "Mon Jan _2 15:04:05 2006"
UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
RFC822      = "02 Jan 06 15:04 MST"
RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339     = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen     = "3:04PM"
like image 34
derekjones562 Avatar answered Sep 22 '22 05:09

derekjones562