Click here to Skip to main content
15,886,639 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can find any date by specify week number of month and week day...


Example...

If i want

What is the date every month on third Thursday


so it should reply...

17/11/2011
15/11/2011
19/1/2012
16/2/2012

how can i achieve this please help....



i am able to do this

C#
DateTime dt = DateTime.Today;
   CultureInfo ciCurr = CultureInfo.CurrentCulture;
   int weekNum = ciCurr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
   weekNum = weekNum / 12;
   string weekday = dt.DayOfWeek.ToString();

i am able to get week number and week day of any date.....

but now i want to find date by given week number and week day....
Posted

to add an extension method called WeekNumber for a DateTime instance here is the code:
C#
public static class DateTimeExtensions
{
    public static int WeekNumber(this System.DateTime value)
    {
        return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(value,CalendarWeekRule.FirstFourDayWeek,DayOfWeek.Monday);
 
    }
}
 
Share this answer
 
v2
Thanks for comment. I updated it.
You the following method:
C#
private List<datetime> GetDateByWeek(DateTime startDate, int weekNumOfMonth, int dayOfWeek)
    {
        List<datetime> dates = new List<datetime>();
        DateTime dt = new DateTime(startDate.Year, startDate.Month, 1);

        for (int i = 0; i < 5; i++)
        {
            int day = (weekNumOfMonth - 1) * 7 - 1 + dayOfWeek - (int)dt.DayOfWeek;
            dates.Add(dt.AddDays(day >= 0 ? day : day + 7));
            dt = dt.AddMonths(1);
        }
        return dates;
    }</datetime></datetime></datetime>


To use this, for example for third week, thursday, just call like this:

List<DateTime> myDates = GetDateByWeek(DateTime.Now, 3, 5);
 
Share this answer
 
v4
Comments
dilip.aim11 17-Nov-11 2:07am    
this is only return next month...
its adding month....
and where we using weekNumOfMonth in this code....

i run this code... it only adding month....
Member 4033260 28-Jun-12 2:45am    
very helpful with some modification....
Member 13171817 9-May-17 6:42am    
how to extract month start date and month end date for a 4-4-5 calender ,i am working on sql plus editior plse help me and suggest me a query

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900