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

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Mastodon, Twitter/X or LinkedIn.

Thanks for reading!