how can I find out the day of the month?

140 Views Asked by At

I have to find out the day of month with given date, let's say I have 01/26/2020 date, now date 26 is 4th Sunday of the Month, how can I find out the day with it's repeatable count in month?

1

There are 1 best solutions below

0
On BEST ANSWER

There is no direct way to achive that.You need to call something like the following code.

 DateTime dateValue = new DateTime(2019, 12, 19);
        int getDayOfWeek = GetWeekNumberOfMonth(dateValue);
        //convert to ordinal 
       string ordinalWeekOfMonth = AddOrdinal(getDayOfWeek);
      Console.WriteLine(ordinalWeekOfMonth + " " + dateValue.DayOfWeek);//output like 2nd sunday

The following dependent methods can be used for calling above code

     public static int GetWeekNumberOfMonth(DateTime date)
    {
        date = date.Date;
        DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
        DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
        if (firstMonthMonday > date)
        {
            firstMonthDay = firstMonthDay.AddMonths(-1);
            firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
        }
        return (date - firstMonthMonday).Days / 7 + 1;
    }

    public static string AddOrdinal(int num)
    {
        if (num <= 0) return num.ToString();

        switch (num % 100)
        {
            case 11:
            case 12:
            case 13:
                return num + "th";
        }

        switch (num % 10)
        {
            case 1:
                return num + "st";
            case 2:
                return num + "nd";
            case 3:
                return num + "rd";
            default:
                return num + "th";
        }

    }