Date and Time format in Golang

Go language is using special formatting tags for date and time, instead of using yyyy-mm-dd as in most languages, it uses a special date to represent format for date and time, this special date and time is:

2006-01-02 15:04:05.0000

which is January 2, 2006, at 15:04:05.0000

Example of printing formatted date and time:

func main() {
today := time.Now()
fmt.Println(today.Format("2006-01-02 15:04:05"))
}

output:

2020-12-18 15:44:43

For Input date and time as string and parsing it to time, we can use time.Parse(layout, adatetimeStr), example:


func main() {
dateInput := "16/11/1975"
adate, err := time.Parse("02/01/2006", dateInput)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(adate.String())
}
}


Output

1975-11-16 00:00:00 +0000 UTC

Leave a Reply