How to Calculate Number of Days in Month using ASP.NET
ASP.NET developers may need to calculate number of days in month for different reasons.
One reason might be to populate a calendar days dropdownlist.
If the ASP.NET developer knows that in February there is 29 days for that year, developer will code in VB.NET or in C# in order to populate day combobox with 29 items beginning from 1 to 29.
Another reasom may be to find the last day in month.
If the ASP.NET developer knows how many days are there for a specific month, he or she will be able to calculate last day of month easily.
Here is a web page from design view which is from a VB.NET sample application project.
The ASP.NET developers will realize that there are three DropDownList items with first two have AutoPostBack properties are equal to True.
The first dropdownlist is used to display year for the web user to select a date from.
The second dropdownlist is used for the web user to pick a month from the displayed list of items.
Here is the ASP.NET source code in HTML view.
Up to now, there is not any problem.
But when it is to decide how many days exist for a specific month year combination, the ASP.NET programmer might need some help.
If you look at the PopulateDaysDDL sub procedure, you will realize that we are using DateTime.DaysInMonth public shared method in order to calculate number of days in the given year month combination.
If ASP.NET developer passes year and month values as input arguments to the public shared DateTime.DaysInMonth method, the return value will be an integer giving the number of days in month requested.
If you look in detail to the above VB.NET code, you will realize that the above code also answers how to calculate last day of month.
The lv_lastdayofmonth local date variable is used to find last day of month requested.
The last day in a month is calculated by using New Date(year, month, day) method.
Since we already know the last day of month, it is easy for VB.NET or CSharp developers to form the date variable using New Date() method passing the year, month and day arguments.