To get the mondays to saturdays in the current month

后端 未结 3 1148
别跟我提以往
别跟我提以往 2021-01-07 06:52

In a month i want to know mondays to sataurdays for the current month eg: in oct month 2011 there are

3-oct-2011 to 8-oct-2011,
10-OCt-11 to 15-Oct-11,          


        
3条回答
  •  旧时难觅i
    2021-01-07 07:13

    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 dates = new List();
    
            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();
    

提交回复
热议问题