Expanding Upon Getting the Days in a Month
I was perusing the ASP.NET forums tonight and saw an entry where the person was asking on help on getting the number of days in a month in .NET. While the asker was making a simple mistake and could not see the forest for the trees, it got me thinking about why there was no overloads to simply return the number of days by passing in a date.
The DateTime class has a Shared method, DaysInMonth, that returns the number of days in the month. It does require the numerical value of the year and the month. While this can be used for just about any instance, it does seem a bit cumbersome in common cases where you have a DateTime value.
The following example will not work.
I preach to my students about the importance of refactoring code into manageable units and to make things as easy to do now and in the future. So I took a few minutes to create a few overloaded methods to accept a DateTime or a SmartDate object and return the number of days. I then extended it to allow a string to be passed into corresponding overloaded methods to return a formatted message with the number of days nicely packed in.
PublicClass ExUtility#Region" DaysInMonth "PublicSharedFunction DaysInMonth(ByVal vDate As DateTime) AsIntegerReturn DateTime.DaysInMonth(vDate.Year, vDate.Month) EndFunctionPublicSharedFunction DaysInMonth(ByVal vDate As SmartDate) AsIntegerReturn DaysInMonth(vDate.Date) EndFunctionPublicSharedFunction DaysInMonth(ByVal vDate As DateTime, ByVal vMessageFormat AsString) AsStringReturnString.Format(vMessageFormat, DaysInMonth(vDate)) EndFunctionPublicSharedFunction DaysInMonth(ByVal vDate As SmartDate, ByVal vMessageFormat AsString) AsIntegerReturn DaysInMonth(vDate.Date, vMessageFormat) EndFunction#End RegionEndClass
Now you can simply call any of these Shared methods to either get the number of days in the month or a predefined message with the value. This should cover many instances you could call, without having to write more code to get the year and month values.