如何在Go中获得给定月份的第一个星期一? [英] How do I get the first Monday of a given month in Go?

查看:63
本文介绍了如何在Go中获得给定月份的第一个星期一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the first Monday of a given month.

我想出的最好方法是循环浏览前7天,并在 .Weekday()=="Monday" 时返回.有更好的方法吗?

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?

推荐答案

通过查看时间中的.Weekday(),您可以计算出第一个星期一.

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

这篇关于如何在Go中获得给定月份的第一个星期一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆