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")
}

Make privacy claims you can back up

Join 800+ subscribers.
One email every few weeks.

I share what I learn building privacy-friendly systems. From confidential computing to Verbond and the occasional Go tip or trick. You can unsubscribe at any time.

A photo of Willem

Written by Willem Schots

I help teams prove what happens to their users' data, and I'm building Verbond, which shows where data can go before third-party code runs.

This site started as a place to learn Go. Most posts are now about privacy-friendly and verifiable systems, with the occasional Go post in between.

Want to talk about your system? Book a 30-minute call, or follow me on Bluesky and LinkedIn.