How to parse a date in Go

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

Are you trying to parse birth dates or other all-day events? Sometimes you only care about the date, not the date and time.

time.Time can still be used to represent such dates. You just need to keep a few things in mind.

  • What notation is used in your data? There are different conventions used around the world.
  • Non-specified elements of a time.Time value will use default values.

Different notations

In the US it’s common to use the MM-DD-YYYY notation, while (most) other countries use DD-MM-YYYY.

You might also encounter the YYYY-MM-DD notation, because this can be alphabetically sorted.

In Go these correspond to the following reference layouts.

Notation Reference layout
"MM-DD-YYYY" "01-02-2006"
"DD-MM-YYYY" "02-01-2006"
"YYYY-MM-DD" "2006-01-02"

If your notation uses doesn’t use - as a divider you can just replace it. For example, 01.02.2006 or 01/02/2006 also work as reference layouts.

Default values

Be aware that all elements of a time.Time that are not part of the date (hours, minutes, seconds, 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 dates below represent 14 January 2024 00:00:00 in the UTC Location.

	// MM-DD-YYYY
	parseAndPrint("01-02-2006", "01-14-2024") // - as divider
	parseAndPrint("01.02.2006", "01.14.2024") // . as divider
	parseAndPrint("01/02/2006", "01/14/2024") // / as divider

	// DD-MM-YYYY
	parseAndPrint("02-01-2006", "14-01-2024") // - as divider
	parseAndPrint("02.01.2006", "14.01.2024") // . as divider
	parseAndPrint("02/01/2006", "14/01/2024") // / as divider

	// YYYY-MM-DD
	parseAndPrint("2006-01-02", "2024-01-14") // - as divider
	parseAndPrint("2006-01-02", "2024-01-14") // . as divider
	parseAndPrint("2006-01-02", "2024-01-14") // / as divider
}
🎓

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!