by Kofo Okesola
Easy date manipulation in Golang with Godate
I have always been and always will be a fan of Carbon and how easy it is to get date manipulation done so efficiently. Being a fan of Carbon and also being a fan of Golang I thought why not write a library called godate. It will do for golang what carbon does for Php, and in this article I will explain how to use it.
The package is mostly a
GoDate struct with its available helper methods, which acts as a wrapper to a
Time struct. It also includes some functions for initializing, e.g.
go get github.com/kofoworola/godate
It also supports go’s new module system. You can simply import it into your project and run. Go will attempt to install the latest version of the package, which is v1.2.0 as of the time of writing this.
Create a new GoDate struct with any of the methods currently available
Note the difference in Timezone, which is why I recommend creating a GoDate struct with a
time.Location object passed.
Once you have a struct you can easily chain methods on the struct to achieve your result like so:
The available compare methods are
IsWeekend . The method names explain what they do:
The most important Difference methods are highlighted below. Although there are more methods included that are also used in the logic of these:
Difference methods that take another
goDate as a parameter calculates the difference as
methodOwner — parameter . A negative difference means the parameter occurs after the
These are the current available String formatting methods. You can also format(you might want to read that if you’re new to dates in golang) this your way by calling the
Some of the extra helper methods and their outputs are listed below:
StartOfWeek methods use
time.Sunday as the default start of the week. This behavior can be changed for the current godate struct by calling
The package is far from complete (and probably never will be). The aim is to provide a robust date handling API similar to and even better (someone’s ambitious here…) than Carbon. So you Go lovers out there like me should make it rain PRs on the repo (and stars :)