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

有些话、适合烂在心里 提交于 2020-01-04 05:22:09

问题


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:


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)))
    }
}


来源:https://stackoverflow.com/questions/19122477/how-do-i-get-the-first-monday-of-a-given-month-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!