It's Go Time: Better Time in Golang
Dealing with time in Go is a pain. The built-in time package doesn’t include much in the way of helper functions. Formatting time is especially difficult; unlike many other languages in the C-family, Go has no support for strftime
-based formatting. Instead, you have to remember a specific date (1/2 3:04:05 2006 -0700) and format that date’s values in the form you’d like to mimic. For instance, if I wanted to format a date into the format mm/dd/yyyy HH:MM:SS
, here’s what you have to do:
Of course, this typically require having to look up the magic date in the docs to make sure you’ve got the right month/day/year. I’m lazy, so naturally I’d rather just have the same strftime
format I’m used to.
Time Flies Like an Arrow; Fruit Flies Like a Banana
The Arrow library provides a C-family style strftime
-based formatting and parsing in Golang (among other helpful date/time functions). Here’s an example of formatting and parsing:
You can also get the time at the beginning of the minute / hour / day / week / month / year.
You can also more easily sleep until specific times:
There are also helpers to get today, yesterday, and UTC times:
And for generating ranges when you need to iterate:
Much easier. There’s more magic not listed here; check out the docs on godoc.org for the full list.