简体   繁体   中英

Get all the dates of the month from Day of week

Is there any way to get all the occuring date for the particular day of the specified month and year..

For example:- If I have Day Thursday then I need all the dates of December 2016. Then collection should contain dates 1/12/2016, 8/12/2016, 15/12/2016, 22/12/2016, 29/12/2016.

You can create a function to get the list of dates of the month based on day of a particular year like

public static List<DateTime> GetDates(int year, int month,string day)
    {
       return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
            .Where(d=>new DateTime(year, month, d).ToString("dddd").Equals(day))            
           .Select(d => new DateTime(year, month, d)).ToList(); 
    }

Now call this function like

var dates=GetDates(2016,12,"Thursday");
    foreach(var d in dates){
    Console.WriteLine(d.ToString());
    }

Output will be

12/1/2016 12:00:00 AM

12/8/2016 12:00:00 AM

12/15/2016 12:00:00 AM

12/22/2016 12:00:00 AM

12/29/2016 12:00:00 AM

Now you have complete list of dates based on a day. You can further use it based on your requirements.

DateTime decFirst = new DateTime(2016, 12, 1);
int offset = (int)decFirst.DayOfWeek;
DateTime decThursday = decFirst.AddDays(offset);

Now you have the first Thursday of December, you should be able to do the rest.

Long form version...

    private void button1_Click(object sender, EventArgs e)
    {
        List<DateTime> Thursdays = DaysOfMonth(2016, 12, DayOfWeek.Thursday);
        foreach(DateTime dt in Thursdays)
        {
            Console.WriteLine(dt.ToString());
        }   
    }

    public static List<DateTime> DaysOfMonth(int year, int month, DayOfWeek day)
    {
        List<DateTime> dates = new List<DateTime>();
        for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
        {
            DateTime dt = new DateTime(year, month, i);
            if (dt.DayOfWeek == day)
            {
                dates.Add(dt);
            }
        }
        return dates;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM