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.Datefunction - To get the parts of a date/time value, use the
time.Timemethods:time.Day() inttime.Month() time.Monthtime.Year() inttime.Date() (year, month,day int)time.Hour() inttime.Minute() inttime.Second() inttime.Nanosecond() inttime.Zone() (namestring,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...