如何根据同月的日期找到一个月中某一天的第5天或结束日期

本文关键字:日期 某一天 一个 结束 5天 何根 | 更新日期: 2023-09-27 18:28:00

我一直在努力寻找一个月中某一天的第5周日期,如第5周周一日期、第5周周二日期、周三。。。依此类推。这个日期可以属于同一个月的任何一周。我试过像

DateTime MonthEventDate=05/01/2016; //Date format in dd/MM/yyyy format
DayOfWeek EventDay="Sunday"; //For Example i want to find 5th Sunday in January Month, but days too will change everytime based on user selection
string SelectedWeek="5"; //Here i'm getting the week in which i need to find the given date i.e, 5th Monday or Tuesday & so on  
if (SelectedWeek == "5")
{
    //Here i tried to add number of days to my initial day to find 5th day date, but every time its returning next month value 
    MonthEventDate = MonthEventDate.AddDays((EventDay < MonthEventDate.DayOfWeek ? 31 : 28) + EventDay - MonthEventDate.DayOfWeek);
}

我知道逻辑是错误的,但我想得到一周中的第5天,如果这一天不存在,返回0。寻求一些指导注意:这里的月份将根据用户输入进行更改,因此如何返回第五天的日期,如果它存在于给定的月份

如何根据同月的日期找到一个月中某一天的第5天或结束日期

这应该会给你第5天(如果有的话)。。。

 DateTime dayInMonth = DateTime.Now;
 DayOfWeek dayToFind = DayOfWeek.Friday;
 var fifth= Enumerable.Range(1, DateTime.DaysInMonth(dayInMonth.Year, dayInMonth.Month))
            .Select(day => new DateTime(dayInMonth.Year, dayInMonth.Month, day))
            .Where(day => day.DayOfWeek == dayToFind)
            .Skip(4)
            .FirstOrDefault();

扩展@Soner Gönül的答案。在输入中,您输入了所需的星期几、所需的月份和所需的年份。在输出时,您可以获得第五周的同一天的日期,或null

    public DateTime? FifthDay(DayOfWeek dayOfWeek, byte monthNum, int year)
    {
        if (monthNum > 12 || monthNum < 1)
        {
            throw new Exception("Month value should be between 1 and 12");
        }
        var searchDate = new DateTime(year, monthNum, 1);
        var weekDay = searchDate.DayOfWeek;
        if (weekDay == dayOfWeek)
        {
            searchDate = searchDate.AddDays(28);
        }
        for (DateTime d = searchDate; d < d.AddDays(7); d = d.AddDays(1))
        {
            if (d.DayOfWeek == dayOfWeek)
            {
                searchDate = searchDate.AddDays(28);
                break;
            }
        }
        if (searchDate.Month == monthNum)
            return searchDate;
        return null;
    }

您可以使用这样的简单数学(不包括验证)

static DateTime? FindDate(int year, int month, DayOfWeek dayOfWeek, int weekOfMonth = 5)
{
    var baseDate = new DateTime(year, month, 1);
    int firstDateOffset = ((int)dayOfWeek - (int)baseDate.DayOfWeek + 7) % 7;
    var date = baseDate.AddDays(firstDateOffset + 7 * (weekOfMonth - 1));
    return date.Month == month ? date : (DateTime?)null; 
}

我认为代码是不言自明的。唯一可能需要解释的技巧是

    int firstDateOffset = ((int)dayOfWeek - (int)baseDate.DayOfWeek + 7) % 7;

当这个月从周五开始,而你要求周一开始时,它会处理这种情况,它是的简短等价物

int firstDateOffset = (int)dayOfWeek - (int)baseDate.DayOfWeek;
if (firstDateOffset < 0) firstDateOffset += 7;

示例中的用法

var monthEventDate = FindDate(2016, 1, DayOfWeek.Sunday, 5);

您可以参考这个演示代码

  int requiredDay = 5; //Day number i.e 0-6(Sunday to SaturDay)
  DateTime day = new DateTime(2016, 1, 1); //Month,year,Date
  if (DateTime.DaysInMonth(day.Year, day.Month) > 28)
  {
      //Get the first day name of the month
       int firstMonthDay = (int)day.DayOfWeek;
       int offset=0;
      //Number of days from the first day for the required day
      if (firstMonthDay <= requiredDay)
          offset = requiredDay - firstMonthDay;
     else
        offset = 7 - firstMonthDay + requiredDay;
//
    DateTime firstoccurence = day.AddDays((double)offset);
    DateTime fifthOccurence = firstoccurence.AddDays(28);
    if (fifthOccurence.Month == firstoccurence.Month)
          MessageBox.Show(fifthOccurence.ToString());
    else
         MessageBox.Show("No 5th Occurence for this day");
   }