kay-B
kay-B

Reputation: 81

Get Number of days in a week

how to calculate number of days in a week? for example 1st week in January 2015 has 4 days, so the function will return 4..... user selects month from a date picker so it could be any year

found a link to a similar question but the page could not be found

Upvotes: 0

Views: 2308

Answers (2)

Artem Kulikov
Artem Kulikov

Reputation: 2296

Try this:

    /// <summary> Get days in a week </summary>
    /// <param name="year">Number of year</param>
    /// <param name="month">Number of month. From 1 to 12</param>
    /// <param name="week">Number of week. From 1 to 5</param>
    /// <returns>Count of days</returns>
    public static int DaysInWeek(int year, int month, int week)
    {
        var weekCounter = 1;
        var daysCounter = 0;
        var dayInMonth = DateTime.DaysInMonth(year, month);
        for (var i = 1; i <= dayInMonth; i++)
        {
            ++daysCounter;
            var date = new DateTime(year, month, i);
            if (date.DayOfWeek == DayOfWeek.Sunday || i == dayInMonth)
            {
                if (weekCounter == week)
                    return daysCounter;

                weekCounter++;
                daysCounter = 0;
            }
        }
        return 7;
    }

Upvotes: 1

hellogoodnight
hellogoodnight

Reputation: 2129

Three cases:

  • For the first week, return the number of days of that week that has the same year as the Sunday of that week.
  • For the last week, return the number of days of that week that has the same year as the Monday of that week.
  • For all other weeks, return 7.

Upvotes: 1

Related Questions