DEV Community

Alireza Bashiri
Alireza Bashiri

Posted on

⌛️The missing strftime in Go

Last night I was reading time package documentation but I couldn't find strftime implementation so I did a little bit of research and I did find out that there's no such thing as strftime in Go time package.

wat

Story short I couldn't find anything close to strftime even in third-party packages then I decided to implement it using cgo without magic and there's it is 🎉, it supports all the standard directives in strftime manual page.

https://github.com/cooldrip/cstrftime

Top comments (4)

Collapse
 
ladydascalie profile image
Benjamin Cable • Edited

This is a great exercise in using cgo, however strftime is certainly not missing, nor should you need to use cgo to do something as trivial as printing formatted time.

Running the following very simple code shows precicely why.

I happen to find the time package much easier and intuitive to use than having to remember cryptic printing macros. I understand if you come from C if the loss of muscle memory might be annoying, but this is a bad solution in my opinion, not just for readability:

cgo, and anything relying on C will not always be available in docker containers. trying to run this in an alpine container for example will end in utter failure, whereas the time package will suffer no such issues.

This means that this solution is not portable, and very much reliant and the platform, which in my opinion makes it unfit for purpose.

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC)

    fmt.Println(
        t.Weekday(),                     // full day
        t.Weekday().String()[0:3],       // abbreviated
        int(t.Weekday()),                // as integer 0 thru 6
        t.Minute(),                      // from 0 thru 59
        fmt.Sprintf("%02d", t.Minute()), // padded
        t.Month(),                       // month
        t.Month().String()[0:3],         // month abbrev.
        t.Location(),                    // time zone name
        t.Format("-0700"),               // offset
    )
}

// prints: Monday, Mon, 1, 0, 00, January, Jan, UTC, +0000

Collapse
 
alirezabashiri profile image
Alireza Bashiri

yeah, it was just an idea and a weekend project ;D

Collapse
 
ladydascalie profile image
Benjamin Cable

I just realised I come across a little abrasive here:

It's great that you built this, and it surely could be useful in a cgo heavy code base!

the time package is one of my favourite from the standard library, precicely because I don't have to remember printing macros for everything.

Some folks are a little put-off by the formatting, but I think it's amazing!

There's a little trick to remembering it by the way:

2006 01 02 15:04:05
0     1  2 3   4  5
Collapse
 
rhymes profile image
rhymes • Edited

I love how you can import "C" and and just use it in Go.