Calculate date from week number

G

Guest

Hi
Im using GregorianCalendar to find out the current years week numbers.
When the user chooses a week number in a dropdown i want to show that week
in a table with the corresponding dates.

For example : the user choses week43 (this week)
so somehow i must calculate what date is startdate that week (monday 18th).
How do i do this with c# ?

all i know is that its-
year: 2004
and week: 43

Ive been thinking about doing it the ugly way .. by taking weeknumber*7 to
get the day of year ... but that wouldnt be accurate since not all weeks have
7 days.

Then I thought about making a loop that goes thru all the days of the year
checking what week that date is in and if its 43 then jump out and return the
date.
But that would be very ugly ... and take unnecessary resources imo.


the Gregorian code is as follows :

GregorianCalendar gCalendar = new GregorianCalendar();
int YearNumber = gCalendar.GetYear(DateTime.Now);
string strMaxDate = YearNumber.ToString() + "-12-31";

int MaxWeekNumber = gCalendar.GetWeekOfYear(Convert.ToDateTime(strMaxDatum),
CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

for(int r = 1; r < MaxWeekNumber+1; r++)
{
selectWeek.Items.Add("Week " + r.ToString());
}
 
H

Hans Kesting

Rustan said:
Hi
Im using GregorianCalendar to find out the current years week numbers.
When the user chooses a week number in a dropdown i want to show that
week in a table with the corresponding dates.

For example : the user choses week43 (this week)
so somehow i must calculate what date is startdate that week (monday
18th). How do i do this with c# ?

all i know is that its-
year: 2004
and week: 43

Ive been thinking about doing it the ugly way .. by taking
weeknumber*7 to get the day of year ... but that wouldnt be accurate
since not all weeks have 7 days.

is that true?
Then I thought about making a loop that goes thru all the days of the
year checking what week that date is in and if its 43 then jump out
and return the date.
But that would be very ugly ... and take unnecessary resources imo.

What you could do:
- check day-of-week and weeknumber for jan 1st of that year
- note: might be in last week of previous year!
- from there calculate startday of week 1
- then add the required number of days ( (weeknum-1)*7), using AddDays()

Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top