Go Cheatsheet - Date & Time
Date & Time
Get current date & time
now := time.Now()
// get current timestamp
ts := now.Unix()
// get current timestamp nano
ts := now.UnixNano()
Format
now.Format("Monday January 2, 2006")
now.Format("01/02/2006 15:04:05")
now.Format("01/02/2006 3PM")
Timezone
tz, _ := time.LoadLocation("America/Chicago")
ccgTime := t.In(tz)
fmt.Println("Chicago Time:", ccgTime)
Parse Time
timeToParse := "2019-02-15T07:33-05:00"
parsed, err := time.Parse("2006-01-02T15:04-07:00", timeToParse)
if err != nil {
panic(err)
}
fmt.Println(parsed)
// parseInLocation will carry timezone info after parsing
parsed2, _ := time.ParseInLocation(
"2/1/2006 3:04 PM ",
"31/7/2015 1:25 AM ",
time.Local)
fmt.Println(parsed2)
Time Diff
start := time.Now()
end := time.Now()
duration := end.Sub(start)
Add date & time
// add 1 year 2 months and 3 days
fmt.Println(now.AddDate(1, 2, 3))
fmt.Println(now.Add(5 * time.Hour))