Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET
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
 
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 16-Nov-11 19:11pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

to add an extension method called WeekNumber for a DateTime instance here is the code:
public static class DateTimeExtensions
{
    public static int WeekNumber(this System.DateTime value)
    {
        return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(value,CalendarWeekRule.FirstFourDayWeek,DayOfWeek.Monday);
 
    }
}
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Thanks for comment. I updated it.
You the following method:
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);
  Permalink  
v4
Comments
dilip.aim11 at 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 at 28-Jun-12 2:45am
   
very helpful with some modification....

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 359
1 Richard MacCutchan 310
2 OriginalGriff 290
3 Sharmanuj 146
4 Jared Sanow 145
0 Sergey Alexandrovich Kryukov 5,969
1 OriginalGriff 5,005
2 CPallini 2,473
3 Richard MacCutchan 1,547
4 Abhinav S 1,507


Advertise | Privacy | Mobile
Web01 | 2.8.140814.1 | Last Updated 18 Nov 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100