DEV Community

loading...

Gostradamus: Better DateTimes in Go

Michael Bykovski
Originally published at Medium ・2 min read

Gostradamus logo

Working with the time package in Go is hard. And I think that a lot of Go programmers see it the same way.

Parsing time, replacing days of a time.Time object and other operations are not natural compared to other languages.
For example parsing a string into a time.Time object looks like this:

import "time"

parsed, err := time.Parse(
    "02.01.2006 15:04:05", 
    "09.04.2020 11:49:54",
)

Or replacing the day of current time object:

import "time"

parsed, err := time.Parse(
    "02.01.2006 15:04:05", 
    "09.04.2020 11:49:54",
)
if err != nil {
    panic(err)
}

replacedDay := time.Date(parsed.Year(), parsed.Month(), 10, parsed.Hour(), parsed.Minute(), parsed.Second(), parsed.Nanosecond(), parsed.Location())

The time package provides all needed functionality but still it takes too much knowledge about the package itself to get to a slim solution.

So I programmed Gostradamus: Better DateTimes in Go to simplify DateTimes handling and parsing/formatting.

Let’s take the examples above and implement them in Gostradamus:

import "github.com/bykof/gostradamus"

parsed, err := gostradamus.Parse(
    "09.04.2020 11:49:54",
    "DD.MM.YYYY HH:mm:ss",
)

Pretty easy huh? And also a really common way to parse dates and times. All parsing tokens can be found here.

The second example would look like this in gostradamus:

import "github.com/bykof/gostradamus"

parsed, err := gostradamus.Parse(
    "09.04.2020 11:49:54",
    "DD.MM.YYYY HH:mm:ss",
)
if err != nil {
    panic(err)
}

replacedDay := parsed.ReplaceDay(10)

Working with DateTimes was never so easy in Go! Gostradamus offers this and much more. Just look up some of the features in the Github Readme or all features in the go.dev reference. It’s also fully compatible with time.Time and can be parsed from and to it.

I hope I could help you a lot with my new package: Gostradamus (Github).

If you like it just leave a ⭐!
If you want to improve or add functionality, feel free to contribute!

Bonus

Gostradamus provides also an easy way to handle timezones. All possible timezones are saved in constants (here).
So you can easily convert from one timezone into another:

import "github.com/bykof/gostradamus"

dateTime := gostradamus.Now()
dateTime = dateTime.InTimeZone(gostradamus.AmericaNewYork)

And also Shifting, Ceiling or Flooring is not a problem:

import "github.com/bykof/gostradamus"

dateTime := gostradamus.Now()
dateTime = dateTime.ShiftDays(-14).CeilMonth()

Next Steps

Next steps in the package would be to offer weeks support and to implement timedeltas, where one could actually subtract one DateTime from another to get the passed time in between.

For example:

dateTime := gostradamus.Now()
... // some computation
gostradamus.Now().Difference(dateTime).Seconds()

Discussion (0)