DEV Community

Cover image for Begin Golang : "time"
marson parulian
marson parulian

Posted on • Updated on


Begin Golang : "time"

This article is a part of Begin Go series: containing my experience learning Go language. Any feedback would be very appreciated.

Parsing time string

In order to complete exercise from exercism's go track, I stumbled on a problem when parsing time string.
I tried to parse 7/13/2020 20:32:00 but I keep getting time with empty value : 0001-01-01 00:00:00 +0000 UTC.

Custom Layout

In Go language, we format and parse time with the pattern-based Layout which has type string. You can read the article in

This is the code I used to parse the string above :

date := "7/13/2020 20:32:00"
t, _ := time.Parse("01/02/2006 15:04:05", date)
// 0001-01-01 00:00:00 +0000 UTC 
Enter fullscreen mode Exit fullscreen mode

With or without leading zero

My mistake that I used leading zero to parse the date and month when I should not used the leading zeros. The parse was successful after I change my code to :

t, _ := time.Parse("1/02/2006 15:04:05", date)
Enter fullscreen mode Exit fullscreen mode

The misuse of leading zero for date, month, etc could lead to potential bugs. So make sure to always consider whether we should use the leading zero or not in Layout to format / parse time.

Remembering The Layout Time Representation

Go has different time representation to format time compared to other languages. Other languages usually use time representation like HH or m to represent month or hour.

Go time representations are as below :

Representation Representing
1 or 01 month
2 or 02 date
15 hour
04 minute
05 second
2006 year
07:00 time offset (time zone)

The question is should we have to lookup for those time representations everytime we use time ? Or maybe there is other way to remember those symbols ?

Looking at the table above, we can see a pattern that matches a well known time format with 1 exception. Code block below will show how I could remember the time representation :

// Well known time format
"Jan 02 2016 15:04:05+07:00"
// Move back the year, right before time offset / time zone.
"Jan 02 15:04:05 2016 +07:00"
// Changing to number presentation, 
// will show a pattern of an incrementing numbers
"01 02 03:04:05 2016 +07:00"
Enter fullscreen mode Exit fullscreen mode



Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<