Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse an ISO 8601 Timestamp in Go?

Tags:

timestamp

time

go

I know I need to use a time layout in Go (as shown here https://golang.org/src/time/format.go) but I can't find the layout for an ISO 8601 timestamp.

If it helps, I get the timestamp from the Facebook API. Here is an example timestamp: 2016-07-25T02:22:33+0000

like image 715
Jonathan Allen Grant Avatar asked Jul 26 '16 17:07

Jonathan Allen Grant


People also ask

How do you parse time in Go?

How to parse datetime in Go. Parse is a function that accepts a string layout and a string value as arguments. Parse parses the value using the provided layout and returns the Time object it represents. It returns an error if the string value specified is not a valid datetime.

How do I read ISO 8601 time?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

How do I convert ISO to timestamp?

Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Copied!

Is ISO 8601 always UTC?

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .


2 Answers

I found this layout to work: "2006-01-02T15:04:05-0700"

like image 138
Jonathan Allen Grant Avatar answered Nov 05 '22 20:11

Jonathan Allen Grant


The problem here is that RFC3339 requires the zone offset to be given as "+00:00" (or "Z" in case of UTC) while ISO8601 allows it to be "+0000".

From RFC3339:

[...]

time-numoffset  = ("+" / "-") time-hour ":" time-minute
time-offset     = "Z" / time-numoffset

[...]

full-time       = partial-time time-offset
date-time       = full-date "T" full-time

So instead of the time.RFC3339 layout

"2006-01-02T15:04:05Z07:00"

you have to use:

"2006-01-02T15:04:05Z0700"
like image 20
AndreKR Avatar answered Nov 05 '22 21:11

AndreKR