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?
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?
By looking at the .Weekday() of the time, you can compute the first Monday.
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)))
}
}