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.
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
}
Get my free newsletter every second week
Used by 500+ developers to boost their Go skills.
"I'll share tips, interesting links and new content. You'll also get a brief guide to time for developers for free."