Time Formatting / Parsing
// Importing necessary packages.
import (
"fmt"
"time"
)
// The main function, where the execution of the program begins.
func main() {
// Creating an alias for fmt.Println for brevity.
p := fmt.Println
// Getting the current time.
t := time.Now()
p(t.Format(time.RFC3339))
// Parsing a time string in RFC3339 format.
t1, e := time.Parse(
time.RFC3339,
"2012-11-01T22:08:41+00:00")
p(t1)
// Formatting time in custom layouts.
p(t.Format("3:04PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
// Parsing a time string with a custom layout.
form := "3 04 PM"
t2, e := time.Parse(form, "8 41 PM")
p(t2)
// Formatting time components manually.
fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
// Parsing a time string in a different layout with an error check.
ansic := "Mon Jan _2 15:04:05 2006"
_, e = time.Parse(ansic, "8:41PM")
p(e)
}Output
Last updated