gpt4 book ai didi

c# - 如何获取下个月的 4. 星期三作为 DateTime?

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:29 24 4
gpt4 key购买 nike

我需要一个函数来给出下个月的第 n 个 DateTime。例如:我需要下个月的第 4 个星期三。

我的代码提供了错误的日期:

private static DateTime FindNextDay(DayOfWeek dayOfWeek, DateTime fday, Int32 instance)
{
DateTime day = new DateTime(fday.Year, fday.Month, 1, fday.Hour, fday.Minute, fday.Second);
// DateTime day is in this Example= 2014-08.01 11.00 AM
if (instance == 2)
{
day = day.AddDays(7);
}
else if (instance == 3)
{
day = day.AddDays(14);
}
else if (instance == 4) //if the 4th week is requested
{
day = day.AddDays(28); // i add 28 days
}
while (day.DayOfWeek != dayOfWeek)
{
day = day.AddDays(1); // and search the wednesday and return it back
}
return day;
}

你能告诉我一个更好的解决方案吗?

最佳答案

像这样的..

获取下个月的第一天,记录您遇到的 星期三 的数量,当您找到一个时将其添加到其中。计数为 4 时返回。

private static DateTime GetFourthWednesday()
{
DateTime firstOfMonth = new DateTime(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month, 1);

int count = 0;
while (count < 4)
{
if (firstOfMonth.DayOfWeek == DayOfWeek.Wednesday)
{
count++;
}

if (count == 4)
{
return firstOfMonth;
}

firstOfMonth = firstOfMonth.AddDays(1);

}

return firstOfMonth;
}

如果今天运行,给出 27/08/2014

关于c# - 如何获取下个月的 4. 星期三作为 DateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699083/

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