When I have a time.Time
:
// January, 29th
t, _ := time.Parse("2006-01-02", "2016-01-29")
How can I get a time.Time
which represents January 31st? This example is trivial, but when there's a date in February, the last day might be 28th or 29th.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.
new(y, m, d) , you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.
Package time
func Date
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
Date returns the Time corresponding to
yyyy-mm-dd hh:mm:ss + nsec nanoseconds
in the appropriate zone for that time in the given location.
The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.
For example, normalizing a date,
package main
import (
"fmt"
"time"
)
func main() {
// January, 29th
t, _ := time.Parse("2006-01-02", "2016-01-29")
fmt.Println(t.Date())
// January, 31st
y,m,_ := t.Date()
lastday:= time.Date(y,m+1,0,0,0,0,0,time.UTC)
fmt.Println(lastday.Date())
}
Output:
2016 January 29
2016 January 31
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With