3

I have been trying to find the 5th week date of a day in a month like 5th week Monday date, 5th week Tue date, Wed... and so on based on the date from the same month. This date could belong to any week of same month. I tried like

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

I know the logic is wrong but i want to get date of 5th day of the week, and if that day is not present, return 0. Looking for some guidance Note: Here Month will change based on User Input, so how to return Date of fifth day, if it exist in the given month

Amar
  • 407
  • 1
  • 5
  • 24
  • Are you looking for the fifth *week* or the fifth *week day* now? I have no idea what you’re trying to do. Can you give some examples? If you’re looking for the fifth week, what if there’s no fifth week for a month? – poke Dec 23 '15 at 11:27
  • Ya... If 5th week is not present then return null or else return date of the 5th day. Ex: In January 2016, we have 5 sunday, so how to find 5th sunday date based on the input given in the question – Amar Dec 23 '15 at 11:29
  • Ya monday or any day which is repeating 5th time in a month – Amar Dec 23 '15 at 11:32

4 Answers4

2

This should give you the 5th day (if there is one) ...

 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();
PaulB
  • 23,264
  • 14
  • 56
  • 75
0

Extending @Soner Gönül's answer. In input you put required day of week, required month and required year. On output you get date of same day of week in fifth weeks, or 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;
    }
Mikhail Tulubaev
  • 4,141
  • 19
  • 31
0

You can use a simple math like this (no validations included)

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

I think the code is self explanatory. The only trick that probably needs explanation is the line

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

which handles the case when let say the month starts in Friday and you asked for Monday, and is a short equivalent of

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

Usage in your example

var monthEventDate = FindDate(2016, 1, DayOfWeek.Sunday, 5);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

You can refer this demo code

  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");
   }
Venkatesh
  • 334
  • 2
  • 11