c# 4.0 - how to calculate the number of the week in a year? -


i calculte number of week in year. i see post

in post acepted answer use code:

public static int getiso8601weekofyear(datetime time) {     // cheat.  if monday, tuesday or wednesday, it'll      // same week# whatever thursday, friday or saturday are,     // , right     dayofweek day = cultureinfo.invariantculture.calendar.getdayofweek(time);     if (day >= dayofweek.monday && day <= dayofweek.wednesday)     {         time = time.adddays(3);     }      // return week of our adjusted day     return cultureinfo.invariantculture.calendar.getweekofyear(time, calendarweekrule.firstfourdayweek, dayofweek.monday); } 

however see problem. number of week repeated if last day of month in sunday.

for example, last day of march of 2013 year in sunday. week number 13th, correct. in april, how c# use 6 weeks in month calculate number of week, first week of april has not day of april, because days belong march because last day of week 30th march. c# says first week of april th 15th week, incorrect, has 14th.

so know if there way calculate number of week in right way.

edit:

i mean this:

in march, last week this:

25 26 27 28 29 30 31

this 13th, correct.

in april, first week is:

1 2 3 4 5 6 7

and week calculated 15th.

so if see march calendar last week calculated 13th , if see april calendar last week of march caluclated 14th. incorrect.

solution:

datetime dtcalendar = calendar.displaydate; int gridrow = (int)getvalue(grid.rowproperty);  // return week of our adjusted day int wueeknumber= system.globalization.cultureinfo.invariantculture.calendar.getweekofyear(dtcalendar, system.globalization.calendarweekrule.firstday, dayofweek.monday);  if (dtcalendar.dayofweek == dayofweek.monday) {     gridrow = gridrow - 1; }  text = (weeknumbe r+ gridrow - 1).tostring();   

thanks.

the problem using wrong calendarweekrule. result want should use firstday. have seen various codes in internet saying should use firstfourdayweek but, after testing, realised "right one" firstday. have tested example , delivers right result: 14th week.

int targetyear = 2013; datetime targetdate = new datetime(targetyear, 4, 1); int week = system.globalization.cultureinfo.currentculture.calendar.getweekofyear(targetdate, system.globalization.calendarweekrule.firstday, dayofweek.monday); 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -