The crazy date/time formatting in Go

Formatting and parsing date/time strings is a very common use-case in programming. A lot of the programming languages I worked with take the same approach for that: Using the Unicode time pattern syntax UTS #35. For me it is always hard to remember the details, especially when it comes to the upper and lower case codes.

A typical format string in Java for an english date would be

    EEE, MM/dd hh:mm:ssa yyyy ZZZ

Fairly simple, but you have to remember that the month part is always upper case, the minute part is always lower case, 12-hour time is the lower case hh, a is the am/pm marker, etc. There a several more pattern letters if you want to get more detailed on the time format.

Go takes a completely new road to date/time formatting. Instead of codes it uses a standard time for describing the desired date/time format. The same date format as above written in Go is:

    Mon, 01/02 03:04:05PM 2006 -0700

As you can see this is a special time counting from one for the month part to six for the year part and seven for the time zone (which is MST). So there a only three things to recall: it starts with the month, the hour part is PM (15 o’clock in 24-hour time) and the day of the week is Monday - instead of all all those abstract time pattern letters.

Now let’s parse and format a simple date string from an english date format to the german date format:

package main

import (
	"fmt"
	"time"
)

func main() {
    // my birthday
    value := "04/19/1979"
    // the format of the value
    parseFormat := "01/02/2006"

    // parse the string into a time object
    time, _ := time.Parse(parseFormat, value)

    // the german output format
    printFormat := "02.01.2006"

    // and print it with the desired format
    fmt.Println(time.Format(printFormat))
}

// => "19.04.1979"

I like this new approach of Go. Writing the standard time down the way yours looks may be strange in the first place, but it’s easy to recall, and it also happens to match the form of your time string, syntactically.