Storing time information
A common problem is storing date/time information in databases, files, and so on in a portable manner, so that it can be interpreted correctly.
How to do it...
You should first identify the exact needs: do you need to store an instant of time or time of day?
- To store an instant of time, do one of the following:
- Store Unix time at the needed granularity (that is,
time.Unix
for seconds,time.UnixMilli
for milliseconds, etc.) - Store UTC time (
time.UTC()
)
- Store Unix time at the needed granularity (that is,
- To store the time of day, store the
time.Duration
value that gives the instant in the day. The following function computes the instant within that day astime.Duration
:func GetTimeOfDay(t time.Time) time.Duration { beginningOfDay:=time.Date(t.Year(),t.Month(),t. Day(),0,0,0,0,t.Location()) return t.Sub(beginningOfDay) }
- To store a date value, you can clear the time portions of
time.Time
:date:=time.Date(t.Year(), t.Month(), t.Day(), 0,0,0,0,t.Location())
Note...