6

Days in a month

 3 years ago
source link: https://yourbasic.org/golang/last-day-month-date/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Days in a month

yourbasic.org/golang
full-moon.jpg

To compute the last day of a month, you can use the fact that time.Date accepts values outside their usual ranges – the values are normalized during the conversion.

To compute the number of days in February, look at the day before March 1.

func main() {
    t := Date(2000, 3, 0) // the day before 2000-03-01
    fmt.Println(t)        // 2000-02-29 00:00:00 +0000 UTC
    fmt.Println(t.Day())  // 29
}

func Date(year, month, day int) time.Time {
    return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}

AddDate normalizes its result in the same way. For example, adding one month to October 31 yields December 1, the normalized form of November 31.

t = Date(2000, 10, 31).AddDate(0, 1, 0) // a month after October 31
fmt.Println(t)                          // 2000-12-01 00:00:00 +0000 UTC

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK