gpt4 book ai didi

c# - 如何找到给定月份的第 n 个 DayOfWeek?

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:59 27 4
gpt4 key购买 nike

我正在尝试查找给定月份(给定年份)的第 n 个 DayOfWeek。

例如:我正在寻找 5 月(2019 年)的第 3 个星期六。

我未能使用 DayOfWeek 扩展方法提出可行的解决方案。我是否必须遍历整个月才能找到第三个星期六?

最佳答案

你当然可以遍历整个月,但我认为这是一种更优雅的方式(取自 here ):

private static DateTime FindTheNthDayOfWeek(int year, int month, int nthOccurrence, DayOfWeek dayOfWeek)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("Invalid month");
}

if (nthOccurrence < 0 || nthOccurrence > 5)
{
throw new ArgumentOutOfRangeException("Invalid nth occurrence");
}

var dt = new DateTime(year, month, 1);

while (dt.DayOfWeek != dayOfWeek)
{
dt = dt.AddDays(1);
}

dt = dt.AddDays((nthOccurrence - 1) * 7);

if (dt.Month != month)
{
throw new ArgumentOutOfRangeException(string.Format("The given month has less than {0} {1}s", nthOccurrence, dayOfWeek));
}

return dt;
}

此私有(private)方法不会循环整个月,但会在找到第一个 DayOfWeek 后停止。然后,您只需为每第 n 次出现添加一周(减去已经添加的一周 ;-))。

关于c# - 如何找到给定月份的第 n 个 DayOfWeek?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55640552/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com