To get the mondays to saturdays in the current month

雨燕双飞 提交于 2019-12-01 13:18:50
var today = DateTime.Today;
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

var dates = Enumerable.Range(1, daysInMonth)
                            .Select(n => new DateTime(today.Year, today.Month, n))
                            .Where(date => date.DayOfWeek != DayOfWeek.Sunday)
                            .ToArray();

This will look at the number of days in the current month, create a DateTime object for each, then only return those dates which are not a Sunday as an array.

var today = DateTime.Today;
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

var dates = Enumerable.Range(1, daysInMonth)
                            .Select(n => new DateTime(today.Year, today.Month, n))
                            .Where(date => date.DayOfWeek != DayOfWeek.Sunday)
                            .SkipWhile(date => date.DayOfWeek != DayOfWeek.Monday)
                            .TakeWhile(date => date.DayOfWeek != DayOfWeek.Monday || (date.DayOfWeek == DayOfWeek.Monday && daysInMonth - date.Day > 7))
                            .ToArray();

This will do the same, except get rid of any Monday -> Saturday ranges which are not in the current month. (Week started in the previous month, or ends in the next).

Edit:

Here is a .NET 2 solution which will do the same thing as my previously posted LINQ solution.

        DateTime today = DateTime.Today;
        int daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

        List<DateTime> dates = new List<DateTime>();

        bool foundFirst = false;

        for (int n = 1; n <= daysInMonth; n++)
        {
            var date = new DateTime(today.Year, today.Month, n);

            // Skip untill we find the first Monday of the month.
            if (date.DayOfWeek != DayOfWeek.Monday && !foundFirst)
                continue;

            foundFirst = true;

            // Add all days except Sundays. 
            if (date.DayOfWeek != DayOfWeek.Sunday)
                dates.Add(date);

            int remainingDays = daysInMonth - n;

            // Verify that there are enough days left in this month to add all days upto the next Saturday.
            if (date.DayOfWeek == DayOfWeek.Saturday && remainingDays < 7)
                break;
        }

        DateTime[] dateArray = dates.ToArray();
suhail

most easy:

        int month = DateTime.Now.Month;
        int year = DateTime.Now.Year;
        int days= DateTime.DaysInMonth(year, month);
        int totalSaturdays = 0;
        for(int i=1;i<=days;i++)
        {
            var day = new DateTime(year, month, i);
            if(day.DayOfWeek==DayOfWeek.Saturday)
            {
                totalSaturdays++;
            }
        }
        Console.WriteLine(("Total Saturdays ="+totalSaturdays.ToString()));
        Console.ReadLine();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!