How to parse datetime in Go

Avatar of the author Willem Schots
13 Jan, 2024
~2 min.
RSS

A common way to format times is a as a “datetime”. A timestamp consisting of a date and a time.

If your application processes such timestamps, you’ll likely want to work with them as time.Time values.

There are some things you need to consider when parsing datetimes in Go:

  • What datetime format are you expecting?
  • What precision are you expecting? Hours, minutes, seconds or even milliseconds?

Format

Dates and times use different notations across the world. For example, un the US it’s common to use the MM-DD-YYYY notation, while (most) other countries use DD-MM-YYYY.

For times, it’s usually a choice between using a 12-hour and a 24 hour notation.

In Go, we use reference layouts to specify such notations.

Some examples of datetime layouts can be found below.

Notation Reference layout
"MM-DD-YYYYTHH:MM:SS" "01-02-2006T15:04:05"
"DD-MM-YYYYTHH:MM:SS" "02-01-2006T15:04:05"
"YYYY-MM-DDTHH:MM:SS" "2006-01-02T15:04:05"
"MM-DD-YYYY HH:MM(AM/PM)" "2006-02-2006 03:04PM"

See the example below for an interactive example.

Other elements default to zero

Be aware that all elements of a time.Time that are not part of the time (years, days, location) will correspond to their default values.

  • Hours, minutes and seconds will default to 0.
  • Location will default to the UTC Location.

If your app needs to handle these times in a different context, be sure to set the appropriate time and location.

main.go
package main

import (
	"fmt"
	"log"
	"time"
)

func parseAndPrint(layout, in string) {
	t, err := time.Parse(layout, in)
	if err != nil {
		log.Fatalf("failed to parse %s: %v", in, err)
	}
	fmt.Println(t)
}

func main() {
	// All datetimes below represent 14 January 2024 13:37:01 in the UTC Location.

	parseAndPrint("01-02-2006T15:04:05", "01-14-2024T13:37:01")
	parseAndPrint("02-01-2006T15:04:05", "14-01-2024T13:37:01")
	parseAndPrint("2006-01-02T15:04:05", "2024-01-14T13:37:01")
	parseAndPrint("01-02-2006 03:04:05PM", "01-14-2024 01:37:01PM")
}

It's getting crazy out there*
Let's cool down a bit?

Join 800+ icecold subscribers

*Political, social and economical trust keeps eroding. AI is adding non-deterministic fuel to the fire.

I'm currently building attested.systems, a way to make systems verifiable by humans and machines. Sharing what I learn along the way.

Avatar of the author
Willem Schots
Edvard Munch, Public domain, via Wikimedia Commons

Hi! I'm the Willem behind willem.dev

I initially created this website to help developers learn Go, but I'm currently working a project that allows humans and machines to verify remote systems.

You can follow me on Bluesky or LinkedIn.

Happy that you're here and thanks for reading! :)