5.5. Date and Time
Basics
Time is represented with the time.Time struct.
The output in the examples below is generated by the Go playground . The Go playground uses a static time to achieve optimal caching performance.
| |
Output:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
Parsing
To parse a string to time.Time we use time.Parse
. Other programming languages often use “format strings” that look something like: yyyy-MM-dd HH:mm:ss. Go does things differently and uses a reference time.
Jan 2 15:04:05 2006 MST
An easy way to remember this value is that it holds, when presented in this order, the values (lined up with the elements above):
1 2 3 4 5 6 -7
Every layout string is a representation of this time stamp. If you want to format a date differently, you must rewrite the above date.
Example:
Mon Jan 2 15:04:05 MST 2006
| |
Output:
2021-02-25 11:06:39 +0000 PST
Thursday
Comparing dates
Dates can be compared with time.Before and time.After
| |
Output:
year3000.After(year2000) = true
year2000.After(year3000) = false
Duration
A time.Duration represents the time between two instants.
To get a duration we can subtract two dates:
| |
Output:
The call took 10s to run.