【问题标题】:How do I get the first Monday of a given month in Go?如何在 Go 中获得给定月份的第一个星期一?
【发布时间】:2013-10-01 17:35:55
【问题描述】:

我正在尝试获取给定月份的第一个星期一。

我能想到的最佳方法是循环播放前 7 天,然后在 .Weekday() == "Monday" 时返回。有没有更好的方法来做到这一点?

【问题讨论】:

  • 你能给我们更多的信息吗?这是一个非常普遍的问题。这很难理解。你必须使用什么样的数据结构?您是否存储了月份和每个月的天数?你真的没有给我们太多细节,我不知道是否有人会直接跳进去“为你做作业”。发布您已有的代码。

标签: time go


【解决方案1】:

通过查看时间的 .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)))
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2021-10-23
    • 2023-03-21
    • 2021-12-04
    • 2011-06-16
    相关资源
    最近更新 更多