winforms - Get week of month C# -
this question has answer here:
- calculate week of month in .net 12 answers
i want find date on week number c# desktop application.
i've been looking on google, none fit needs.
how week in month example below?
example:
i want january 6, 2014 = first week of january
january 30, 2014 = fourth week of january
but 1 february 2014 = week 4 in january
and 3 february 2014 first week in february
here method:
static int getweeknumberofmonth(datetime date) { date = date.date; datetime firstmonthday = new datetime(date.year, date.month, 1); datetime firstmonthmonday = firstmonthday.adddays((dayofweek.monday + 7 - firstmonthday.dayofweek) % 7); if (firstmonthmonday > date) { firstmonthday = firstmonthday.addmonths(-1); firstmonthmonday = firstmonthday.adddays((dayofweek.monday + 7 - firstmonthday.dayofweek) % 7); } return (date - firstmonthmonday).days / 7 + 1; } test:
console.writeline(getweeknumberofmonth(new datetime(2014, 1, 6))); // 1 console.writeline(getweeknumberofmonth(new datetime(2014, 1, 30))); // 4 console.writeline(getweeknumberofmonth(new datetime(2014, 2, 1))); // 4 console.writeline(getweeknumberofmonth(new datetime(2014, 2, 3))); // 1
Comments
Post a Comment