Count number of Mondays in a given date range

后端 未结 15 1171
南旧
南旧 2020-11-28 09:35

Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.

I am currently working in C#.

相关标签:
15条回答
  • 2020-11-28 09:55
    You could try this, if you want to get specific week days between two dates
    public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
    {
        var selectedDates = new List<DateTime>();
    
        if (startDate >= endDate)
            return selectedDates; //No days to return
    
        if (daysToCheck == null || daysToCheck.Count == 0)
            return selectedDates; //No days to select
    
        try
        {
            //Get the total number of days between the two dates
            var totalDays = (int)endDate.Subtract(startDate).TotalDays;
    
            //So.. we're creating a list of all dates between the two dates:
            var allDatesQry = from d in Enumerable.Range(1, totalDays)
                                 select new DateTime(
                                                      startDate.AddDays(d).Year,
                                                      startDate.AddDays(d).Month,
                                                      startDate.AddDays(d).Day);
    
            //And extracting those weekdays we explicitly wanted to return
            var selectedDatesQry = from d in allDatesQry
                                      where daysToCheck.Contains(d.DayOfWeek)
                                      select d;
    
            //Copying the IEnumerable to a List
            selectedDates = selectedDatesQry.ToList();
        }
        catch (Exception ex)
        {
            //Log error
            //...
    
            //And re-throw
            throw;
        }
        return selectedDates;
    }
    
    0 讨论(0)
  • 2020-11-28 09:55

    This will return a collection of integers showing how many times each day of the week occurs within a date range

        int[] CountDays(DateTime firstDate, DateTime lastDate)
        {
            var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;
            var weeks = (int)Math.Floor(totalDays / 7);
    
            var result = Enumerable.Repeat<int>(weeks, 7).ToArray();
            if (totalDays % 7 != 0)
            {
                int firstDayOfWeek = (int)firstDate.DayOfWeek;
                int lastDayOfWeek = (int)lastDate.DayOfWeek;
                if (lastDayOfWeek < firstDayOfWeek)
                    lastDayOfWeek += 7;
                for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)
                    result[dayOfWeek % 7]++;
            }
            return result;
        }
    

    Or a slight variation which lets you do FirstDate.TotalDaysOfWeeks(SecondDate) and returns a Dictionary

        public static Dictionary<DayOfWeek, int> TotalDaysOfWeeks(this DateTime firstDate, DateTime lastDate)
        {
            var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;
            var weeks = (int)Math.Floor(totalDays / 7);
    
            var resultArray = Enumerable.Repeat<int>(weeks, 7).ToArray();
            if (totalDays % 7 != 0)
            {
                int firstDayOfWeek = (int)firstDate.DayOfWeek;
                int lastDayOfWeek = (int)lastDate.DayOfWeek;
                if (lastDayOfWeek < firstDayOfWeek)
                    lastDayOfWeek += 7;
                for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)
                    resultArray[dayOfWeek % 7]++;
            }
            var result = new Dictionary<DayOfWeek, int>();
            for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++)
                result[(DayOfWeek)dayOfWeek] = resultArray[dayOfWeek];
            return result;
        }
    
    0 讨论(0)
  • 2020-11-28 09:59

    A bit Modified Code is here works and Tested by me

            private int CountDays(DayOfWeek day, DateTime startDate, DateTime endDate)
            {
                int dayCount = 0;
    
                for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))
                {
                    if (dt.DayOfWeek == day)
                    {
                        dayCount++;
                    }
                }
    
                return dayCount;
            }
    

    Example:

    int Days = CountDays(DayOfWeek.Friday, Convert.ToDateTime("2019-07-04"), 
                 Convert.ToDateTime("2019-07-27")).ToString();
    
    0 讨论(0)
  • 2020-11-28 10:08

    Try this:

    static int CountDays(DayOfWeek day, DateTime start, DateTime end)
    {
        TimeSpan ts = end - start;                       // Total duration
        int count = (int)Math.Floor(ts.TotalDays / 7);   // Number of whole weeks
        int remainder = (int)(ts.TotalDays % 7);         // Number of remaining days
        int sinceLastDay = (int)(end.DayOfWeek - day);   // Number of days since last [day]
        if (sinceLastDay < 0) sinceLastDay += 7;         // Adjust for negative days since last [day]
    
        // If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.
        if (remainder >= sinceLastDay) count++;          
    
        return count;
    }
    
    0 讨论(0)
  • 2020-11-28 10:08

    Add the smallest possible number to make the first day a Monday. Subtract the smallest possible number to make the last day a Monday. Calculate the difference in days and divide by 7.

    0 讨论(0)
  • 2020-11-28 10:09

    Since you're using C#, if you're using C#3.0, you can use LINQ.

    Assuming you have an Array/List/IQueryable etc that contains your dates as DateTime types:

    DateTime[] dates = { new DateTime(2008,10,6), new DateTime(2008,10,7)}; //etc....
    
    var mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday); // = {10/6/2008}
    

    Added:

    Not sure if you meant grouping them and counting them, but here's how to do that in LINQ as well:

    var datesgrouped = from d in dates
                       group d by d.DayOfWeek into grouped
                       select new { WeekDay = grouped.Key, Days = grouped };
    
    foreach (var g in datesgrouped)
    {
        Console.Write (String.Format("{0} : {1}", g.WeekDay,g.Days.Count());
    }
    
    0 讨论(0)
提交回复
热议问题