How do I get the first Monday of a given month in Go?

huangapple go评论71阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

// 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 &lt;= 12; m++ {
		fmt.Println(m, FirstMonday(2013, time.Month(m)))
	}
}

huangapple
  • 本文由 发表于 2013年10月2日 01:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/19122477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定