Date/time components
When working with date values, you often have to compose a date/time from its components or need to access the components of a date/time value. This recipe shows how it can be done.
How to do it...
- To build a date/time value from parts, use the
time.Date
function - To get the parts of a date/time value, use the
time.Time
methods:time.Day() int
time.Month() time.Month
time.Year() int
time.Date() (year, month,
day int)
time.Hour() int
time.Minute() int
time.Second() int
time.Nanosecond() int
time.Zone() (name
string,offset int)
time.Location() *time.Location
time.Date
will create a time value from its components:
d := time.Date(2020, 3, 31, 15, 30, 0, 0, time.UTC) fmt.Println(d) // 2020-03-31 15:30:00 +0000 UTC
The output will be normalized, as follows:
d := time.Date(2020, 3, 0, 15, 30, 0, 0, time.UTC) fmt.Println(d) // 2020-02-29 15:30:00 +0000 UTC
Since the day of the month starts from 1, creating a date with a 0
day will result in the last...