Click here to Skip to main content
15,904,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How to get the current date when i pass the parameter as week and year.

Example,

I have 25-2011 (week and year), How to get the date for this week and year...?
Posted

 
Share this answer
 
Heres the logic:
1. Find out the Day of Week of Jan 1 of the year (Sunday or Monday etc......)
2. Based on results from step 1, determine the first Sunday of the year.
3. If Jan 1st itself is a Sunday, that becomes the first week, else it is the second week.
4. Use results from step 3 to determine the days for any specific week # using the fact that a week has 7 days.
 
Share this answer
 
Try:
C#
private static DateTime GetDateFromWeek(int year, int weekOfYear)
   {
   DateTime jan1 = new DateTime(year, 1, 1);
   int daysOffset = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;
   DateTime firstMonday = jan1.AddDays(daysOffset);
   int firstWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(jan1, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
   if (firstWeek <= 1)
      {
      weekOfYear -= 1;
      }
   return firstMonday.AddDays(weekOfYear * 7);
   }
Can't remember where I got it, but there you go...
 
Share this answer
 
Use System.DateTime. Take a first day of the year for initial value, by number of week calculate number of days (multiply by 7 minus one) and use System.DateTime.AddDays. See http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^].

—SA
 
Share this answer
 
Define a function as:
C#
private DateTime GetDateByWeekAndYear(int year, int WeekNo)
       {
           DateTime dt = new DateTime(year, 1, 1); //initialize date to 1-jan-year
           CultureInfo ci = CultureInfo.CurrentCulture;
           dt = ci.Calendar.AddWeeks(dt, WeekNo); // Add required no of weeks
           return dt;

       }


Call the method by passing year and week no
C#
DateTime dt =  GetDateByWeekAndYear(2011,25);


Here is the another way to implement the method:
C#
private DateTime GetDateByWeekAndYear(int year, int WeekNo)
        {
            DateTime dt = new DateTime(year, 1, 1); //initialize date to 1-jan-year

            while (dt.DayOfWeek != DayOfWeek.Monday)
            {
                dt = dt.AddDays(1); //complete the first week till sunday, this is first week
            }
            dt = dt.AddDays((WeekNo - 2) * 7); //Already date is incremented till first week, add 7*(WeekNo - 2) to get 1st day of that week

            return dt;
        }
 
Share this answer
 
v2

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