英文:
How do I get the first Monday of a given month in Go?
问题
我正在尝试获取给定月份的第一个星期一。
我能想到的最好的方法是循环遍历前七天,当 .Weekday() == "Monday"
时返回。是否有更好的方法来实现这个目标?
英文:
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?
答案1
得分: 14
通过查看时间的 .Weekday(),可以计算出第一个星期一。
package main
import (
"fmt"
"time"
)
// FirstMonday 返回给定月份中第一个星期一的日期。
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)))
}
}
请注意,这是一个用 Go 语言编写的程序,用于计算给定年份中每个月份的第一个星期一的日期。
英文:
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)))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论