gpt4 book ai didi

c# - 判断某月第一天、最后一天等的函数。

转载 作者:太空狗 更新时间:2023-10-30 00:59:03 33 4
gpt4 key购买 nike

我正在创建一个调度程序并且需要能够在 C# 中执行以下操作:

  1. 找到 2012 年 6 月的第一个星期二
  2. 找到 2008 年 3 月的最后一个星期五
  3. 查找 2013 年 1 月的每个星期六
  4. 找到 2009 年 7 月的第 3 个星期五
  5. 查找 future 3 个月内的每个星期六
  6. 查找 2018 年 3 月的每一天

返回的结果应该是 DateTimeList<DateTime> .

最佳答案

以下是查找给定月份中第一个/最后一个指定星期几的方法:

public DateTime GetFirstDayOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek)
{
DateTime dt = new DateTime(year, month, 1);
int first = (int)dt.DayOfWeek;
int wanted = (int)dayOfWeek;
if (wanted < first)
wanted += 7;
return dt.AddDays(wanted - first);
}

public DateTime GetLastDayOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek)
{
int daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month);
DateTime dt = new DateTime(year, month, daysInMonth);
int last = (int)dt.DayOfWeek;
int wanted = (int)dayOfWeek;
if (wanted > last)
last += 7;
return dt.AddDays(wanted - last);
}

从中,您可以轻松找到其他问题的答案...只需添加 7 天即可找到您要查找的那一天的下一次出现


编辑:考虑更多,以扩展方法的形式使用它会非常方便,例如:

Console.WriteLine("Next monday : {0}", DateTime.Today.Next(DayOfWeek.Monday));
Console.WriteLine("Last saturday : {0}", DateTime.Today.Previous(DayOfWeek.Saturday));

这里是实现:

public static class DateExtensions
{
public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek)
{
int start = (int)from.DayOfWeek;
int wanted = (int)dayOfWeek;
if (wanted < start)
wanted += 7;
return from.AddDays(wanted - start);
}

public static DateTime Previous(this DateTime from, DayOfWeek dayOfWeek)
{
int end = (int)from.DayOfWeek;
int wanted = (int)dayOfWeek;
if (wanted > end)
end += 7;
return from.AddDays(wanted - end);
}
}

它可能比我建议的第一种方法更灵活......有了它,你可以轻松地做这样的事情:

// Print all Sundays between 2009/01/01 and 2009/03/31
DateTime from = new DateTime(2009, 1, 1);
DateTime to = new DateTime(2009, 3, 31);
DateTime sunday = from.Next(DayOfWeek.Sunday);
while(sunday <= to)
{
Console.WriteLine(sunday);
sunday = sunday.AddDays(7);
}

关于c# - 判断某月第一天、最后一天等的函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1506378/

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