-3

I need list of weeks with starting and ending dates by giving int year and int month,

Example Result,

Week1 = 7/1/2012 to 7/1/2012

Week2 = 7/2/2012 to 7/8/2012

Week3 = 7/9/2012 to 7/15/2012

Week4 = 7/16/2012 to 7/22/2012

Week5 = 7/23/2012 to 7/29/2012

Week6 = 7/30/2012 to 7/31/2012

4

2 回答 2

6

Something like this should work:

// using System.Globalization;
var calendar = CultureInfo.CurrentCulture.Calendar;
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
var weekPeriods =
Enumerable.Range(1, calendar.GetDaysInMonth(year, month))
          .Select(d =>
          {
              var date = new DateTime(year, month, d);
              var weekNumInYear = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, firstDayOfWeek);
              return new { date, weekNumInYear };
          })
          .GroupBy(x => x.weekNumInYear)
          .Select(x => new { DateFrom = x.First().date, To = x.Last().date })
          .ToList();

Of course you can change the Culture (here I have used the CurrentCulture).

于 2012-07-13T07:23:40.747 回答
2

check this one and edit according to your need

// Get the weeks in a month

        DateTime date = DateTime.Today;
        // first generate all dates in the month of 'date'
        var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
        // then filter the only the start of weeks
        var weekends = (from d in dates
                       where d.DayOfWeek == DayOfWeek.Monday
                       select d).ToList();
        foreach (var d in weekends)
        {
            Console.WriteLine(d);
        }
        Console.Write(weekends);
        Console.ReadLine();

hope it help you.

you can also take a look here for other stuff HERE

于 2012-07-13T06:58:43.500 回答