Date/time arithmetic
Date/time arithmetic is necessary to answer questions such as the following:
- How long did it take to complete an operation?
- What time will it be after 5 minutes?
- How many days are there until next month?
This recipe shows how you can answer these questions using the time
package.
How to do it...
- To find out how much time has passed between two instances in time, use the
Time.Sub
method to subtract them. - To find the duration from now to a later time, use
time.Until(laterTime)
. - To find how much time has passed since a given time, use
time.Since(beforeTime)
. - To find out what time it will be after a certain duration, use the
Time.Add
method. Use negative duration to find the time before a certain duration. - To add/subtract years, months, or days to/from a time, use the
Time.AddDate
method. - To compare two
time.Time
values, use the following:Time.Equal
to check whether two time values represent the same instanceTime...