I'm trying to get the first Monday of a given month.
Best way I can come up with is to loop through first seven days and return when .Weekday() == "Monday"
. Is there a better way to do this?
通过查看时间的 .Weekday(),您可以计算出第一个星期一。
package main
import (
"fmt"
"time"
)
// FirstMonday returns the day of the first Monday in the given month.
func FirstMonday(year int, month time.Month) int {
t := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
return (8-int(t.Weekday()))%7 + 1
}
func main() {
for m := 1; m <= 12; m++ {
fmt.Println(m, FirstMonday(2013, time.Month(m)))
}
}