Skip to content

⌛️The missing strftime in Go

alirezabashiri profile image Alireza Bashiri github logo ・1 min read

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.


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.

twitter logo DISCUSS (4)
markdown guide

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 (

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

        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


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


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

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

Classic DEV Post from Jul 30 '19

What's your favorite question to be asked?

Alireza Bashiri profile image
I write software.